package com.redrield.shortify.util

import com.google.gson.Gson
import com.redrield.shortify.common.Shortener
import com.redrield.shortify.common.ShortifyException
import ninja.leaping.configurate.commented.CommentedConfigurationNode
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import java.io.IOException
import java.net.URL

object ShortifyUtil {
    private val URL_PATTERN = Regex("((mailto:|(news|(ht|f)tp(s?))://)\\S+)")

    val GSON = Gson()

    val CLIENT: CloseableHttpClient = HttpClientBuilder.create().build()

    val ACTIVE_SHORTENERS = HashMap<String, Shortener>()

    @Throws(ShortifyException::class)
    fun shortenAll(txt: String, minLn: Int, shortener: Shortener): String {
        val matches = URL_PATTERN.findAll(txt)

        val allShortens = HashMap<String, String>()
        matches.map(MatchResult::value).filter { it.length >= minLn }
                .filter(ShortifyUtil::urlValid)
                .forEach { allShortens.put(it, shortener.getShortenedUrl(it)) }

        var final = txt
        allShortens.forEach { k, v -> final = final.replace(k, v) }
        return final
    }

    fun validateConfiguration(config: CommentedConfigurationNode): Boolean {
        if (config.getNode("shortener").string == "bitly" && config.getNode("bitly").isVirtual) {
            return false
        } else if (config.getNode("shortener").string == "googl" && config.getNode("googl").isVirtual) {
            return false
        }
        return true
    }

    fun urlValid(url: String): Boolean {
        try {
            URL(url).openStream()
            return true
        }catch(e: IOException) {
            e.printStackTrace()
            return false
        }
    }
}