package com.base.browserwhite.utils

import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.searchEngineSp
import java.net.MalformedURLException
import java.net.URL
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

object LinkSearchUtils {
    fun handleInput(
        input: String,
        loadUrl: (url: String) -> Unit,
        performSearch: (search: String) -> Unit
    ) {
        // 去除输入字符串两端的空白字符
        val tempInput = input.trim { it <= ' ' }

        // 检查输入是否看起来像是一个网址
        if (isLikelyUrl(tempInput)) {
            // 补齐协议并加载网址
            val formattedUrl = addProtocolIfNeeded(tempInput)
            loadUrl(formattedUrl)
        } else {
            // 作为搜索关键词处理
            performSearch(input)
        }
    }

    /**
     * 检查输入是否可能是一个网址。
     */
    private fun isLikelyUrl(input: String): Boolean {
        // 简单的启发式检查，适用于网址识别
        return input.matches(".*\\..+".toRegex()) && !input.matches(".*\\s.*".toRegex())
    }

    /**
     * 如果输入的字符串没有明确的协议部分，补齐 "http://" 或 "https://"。
     */
    private fun addProtocolIfNeeded(input: String): String {
        // 如果输入以 "http://" 或 "https://" 开头，不做改变
        if (input.startsWith("http://") || input.startsWith("https://")) {
            return input
        } else if (input.startsWith("www.")) {
            return "http://$input"
        } else if (input.contains(".")) {
            return "https://$input"
        }
        // 其他情况，无法确定是网址还是搜索词
        return input
    }

    fun getSearchUrl(
        searchText: String,
        searchEngine: String = ConstObject.searchEngineSp
    ): String {
        val action = when (searchEngine) {
            ConstObject.GOOGLE -> ::getGoogleSearch
            ConstObject.BING -> ::getBingSearch
            ConstObject.YAHOO -> ::getYahooSearch
            ConstObject.DUCKDUCKGO -> ::getDuckDuckGoSearch
            ConstObject.YANDEX -> ::getYandexSearch
            ConstObject.BAIDU -> ::getBaiduSearch
            else -> ::getGoogleSearch
        }
        return action.invoke(searchText)
    }

    fun isValidUrl(urlString: String?): Boolean {
        return try {
            // 尝试将字符串转换为URL对象
            URL(urlString)
            true
        } catch (e: MalformedURLException) {
            // 如果转换失败，说明不是有效的URL
            false
        }
    }

    fun isMatchesUrl(urlString: String): Boolean {
        val pattern = "^(https?://)?(www\\.)?[a-z0-9]+\\.[a-z0-9.-]+\\.[a-z]{2,6}(:[0-9]{1,5})?(/.*)?$"
        return urlString.matches(pattern.toRegex())
    }

    fun getWWWSearch(content: String): String? {
        if (isValidUrl(content) || isMatchesUrl(content)) {
            return if (content.contains("http") or content.contains("https")) {
                content
            } else {
                "https://$content"
            }
        }
        return null
    }

    fun getGoogleSearch(content: String): String {
        val base = "https://www.google.com/"
        val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
        val search = "search?q=${encodedQuery}&oq=${encodedQuery}"
        return "$base$search"
    }

    fun getBingSearch(content: String): String {
        //https://cn.bing.com/search?q=aaa&form=QBLHCN&sp=-1&lq=0&pq=aaa&sc=10-3&qs=n&sk=&cvid=CBA1E2A2A9124EBB9C9970DC69330095&ghsh=0&ghacc=0&ghpl=
        val base = "https://cn.bing.com/"
        val search = "search?q=${content}&form=QBLHCN&sp=-1&lq=0&pq=${content}"
        return "$base$search"
    }


    fun getYahooSearch(content: String): String {
        val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())

        return "https://search.yahoo.com/search?p=$encodedQuery"
    }

    fun getDuckDuckGoSearch(content: String): String {
        val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
        return "https://www.duckduckgo.com/?q=encodedQuery"
    }

    fun getYandexSearch(content: String): String {
        val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
        return "https://yandex.com/search/?text=$encodedQuery"
    }

    fun getBaiduSearch(content: String): String {
        val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
        return "https://www.baidu.com/s?wd=$encodedQuery"
    }

    fun getSpSearchAction(content: String): String {

        val action: (content: String) -> String = when (searchEngineSp) {
            ConstObject.GOOGLE -> ::getGoogleSearch
            ConstObject.BING -> ::getBingSearch
            ConstObject.YAHOO -> ::getYahooSearch
            ConstObject.DUCKDUCKGO -> ::getDuckDuckGoSearch
            ConstObject.YANDEX -> ::getYandexSearch
            ConstObject.BAIDU -> ::getBaiduSearch
            else -> ::getGoogleSearch
        }
        return action.invoke(content)

    }


}
