package com.base.browserwhite.help

import com.base.browserwhite.utils.LogEx
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder

object SearchTipUtils {

    private val TAG = "SearchTipUtils"

    fun getSearchTip(q: String): List<String>? {

        val encodedQuery = URLEncoder.encode(q, "UTF-8")

        val url = "https://www.google.com/complete/search?q=$q&cp=3&client=gws-wiz&xssi=t&hl=en"

        try {
            val conn: HttpURLConnection = URL(url).openConnection() as HttpURLConnection
            conn.setRequestMethod("GET")
            conn.connectTimeout = 5000
//            conn.setRequestProperty("Accept-Charset", "UTF-8")

            if (200 == conn.getResponseCode()) {
                val reader = BufferedReader(InputStreamReader(conn.inputStream))
                val sb = StringBuilder()
                var line: String? = reader.readLine()
                while (line != null) {
                    sb.append(line)
//                    sb.append("\n") // 保留换行符
                    line = reader.readLine()
                }
                reader.close() // 关闭流

                return parseSearchTip(sb.toString())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

    fun parseSearchTip(content: String): ArrayList<String> {
        LogEx.logDebug(TAG, "content=$content")

//        val ss = ")]}'" +
//                "[[[\"cathay pacific\",46,[512,433,465,131,199],{\"lm\":[],\"zh\":\"Cathay Pacific\",\"zi\":\"\",\"zp\":{\"gs_ssp\":\"eJzj4tTP1TcwNC7MzVZgNGB0YPDiS04syUisVChITM5My0wGAIIACQ8\"},\"zs\":\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcQtzgOhVqh-vupszYF_gIbWcyVwIdRMfpI_ba906tve\\u0026s\\u003d10\"}],[\"cat\\u003cb\\u003ehay pacific hk\\u003c\\/b\\u003e\",0,[512,433,131]],[\"cat\",46,[512,433,131],{\"lm\":[],\"zh\":\"Cat\",\"zi\":\"Animal\",\"zp\":{\"gs_ssp\":\"eJzj4tDP1TcwrCyqMGD0Yk5OLAEAIl8EWA\"},\"zs\":\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcT4e_IR-4BLrmcChIUBwzHJ0xFnhVRLPaDq3S4Zh-VcV95KdCNROxchRNy5Gg\\u0026s\\u003d10\"}],[\"cat\\u003cb\\u003ehay pacific online check in\\u003c\\/b\\u003e\",0,[512]],[\"cat\\u003cb\\u003ealog hk\\u003c\\/b\\u003e\",0,[512,433,131,650]],[\"cat\\u003cb\\u003ealog\\u003c\\/b\\u003e\",0,[512]],[\"cat\\u003cb\\u003ehay pacific booking\\u003c\\/b\\u003e\",0,[512,433]],[\"cat\\u003cb\\u003ehay pacific flight status\\u003c\\/b\\u003e\",0,[512]],[\"cat\\u003cb\\u003ehay shop\\u003c\\/b\\u003e\",0,[512,433,650]],[\"cat\\u003cb\\u003ehay check in\\u003c\\/b\\u003e\",0,[512,433]]],{\"ag\":{\"a\":{\"40024\":[\"\",\"\",1,20]}},\"q\":\"-26moM5WZmS00EjrsMoHYLIF1Zo\"}]"
        val list = arrayListOf<String>()

        try {
            val json = content.replace(")]}'", "")
            val jsonArray = JSONArray(json)
            val firstArray = jsonArray.getJSONArray(0)

            for (i in 0 until firstArray.length()) {
                val subArray = firstArray.getJSONArray(i)
                val name = subArray.getString(0).replace("<b>", "").replace("</b>", "")

//                list.add(convertUnicodeToChinese(name))
                val decodeContent = decodeHtmlEntities(name)
                LogEx.logDebug(TAG, "decodeContent=$decodeContent")
                list.add(decodeContent)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return list
    }


    fun decodeHtmlEntities(input: String): String {
        val regex = "&#(\\d+);".toRegex()
        val ss = regex.replace(input) { matchResult ->
            val code = matchResult.groupValues[1]
            LogEx.logDebug(TAG, "decodeHtmlEntities code=$code")
            val unicodeInt = code.toInt()
            val chinese = unicodeInt.toChar().toString()
            LogEx.logDebug(TAG, "decodeHtmlEntities chinese=$chinese")
            chinese
        }
        return ss
    }


    private fun test() {
        //        val ss = "[\n" +
//                "\t[\n" +
//                "\t\t[\"cathay pacific\", 46, [512, 433, 465, 131, 199], {\n" +
//                "\t\t\t\"lm\": [],\n" +
//                "\t\t\t\"zh\": \"Cathay Pacific\",\n" +
//                "\t\t\t\"zi\": \"\",\n" +
//                "\t\t\t\"zp\": {\n" +
//                "\t\t\t\t\"gs_ssp\": \"eJzj4tTP1TcwNC7MzVZgNGB0YPDiS04syUisVChITM5My0wGAIIACQ8\"\n" +
//                "\t\t\t},\n" +
//                "\t\t\t\"zs\": \"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcQtzgOhVqh-vupszYF_gIbWcyVwIdRMfpI_ba906tve\\u0026s\\u003d10\"\n" +
//                "\t\t}],\n" +
//                "\t\t[\"cat\\u003cb\\u003ehay pacific hk\\u003c\\/b\\u003e\", 0, [512, 433, 131]],\n" +
//                "\t\t[\"cat\", 46, [512, 433, 131], {\n" +
//                "\t\t\t\"lm\": [],\n" +
//                "\t\t\t\"zh\": \"Cat\",\n" +
//                "\t\t\t\"zi\": \"Animal\",\n" +
//                "\t\t\t\"zp\": {\n" +
//                "\t\t\t\t\"gs_ssp\": \"eJzj4tDP1TcwrCyqMGD0Yk5OLAEAIl8EWA\"\n" +
//                "\t\t\t},\n" +
//                "\t\t\t\"zs\": \"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcT4e_IR-4BLrmcChIUBwzHJ0xFnhVRLPaDq3S4Zh-VcV95KdCNROxchRNy5Gg\\u0026s\\u003d10\"\n" +
//                "\t\t}],\n" +
//                "\t\t[\"cat\\u003cb\\u003ehay pacific online check in\\u003c\\/b\\u003e\", 0, [512]],\n" +
//                "\t\t[\"cat\\u003cb\\u003ealog hk\\u003c\\/b\\u003e\", 0, [512, 433, 131, 650]],\n" +
//                "\t\t[\"cat\\u003cb\\u003ealog\\u003c\\/b\\u003e\", 0, [512]],\n" +
//                "\t\t[\"cat\\u003cb\\u003ehay pacific booking\\u003c\\/b\\u003e\", 0, [512, 433]],\n" +
//                "\t\t[\"cat\\u003cb\\u003ehay pacific flight status\\u003c\\/b\\u003e\", 0, [512]],\n" +
//                "\t\t[\"cat\\u003cb\\u003ehay shop\\u003c\\/b\\u003e\", 0, [512, 433, 650]],\n" +
//                "\t\t[\"cat\\u003cb\\u003ehay check in\\u003c\\/b\\u003e\", 0, [512, 433]]\n" +
//                "\t], {\n" +
//                "\t\t\"ag\": {\n" +
//                "\t\t\t\"a\": {\n" +
//                "\t\t\t\t\"40024\": [\"\", \"\", 1, 20]\n" +
//                "\t\t\t}\n" +
//                "\t\t},\n" +
//                "\t\t\"q\": \"-26moM5WZmS00EjrsMoHYLIF1Zo\"\n" +
//                "\t}\n" +
//                "]"

        val ss = ")]}'\n" +
                "[[[\"&#29483;&#21674;&#22823;&#25136;abc&#29229;\",46,[512],{\"lm\":[],\"zh\":\"a&#29483;b&#21674;c&#22823;&#25136;&#29229;\",\"zi\":\"&#35987;&#21674;&#22823;&#25136;&#29229; \\u2014 &#38651;&#29609;&#36938;&#25138;\",\"zp\":{\"gs_ssp\":\"eJzj4tVP1zc0TDczTTfLMKg0YPTif96z-umkVU-XLH_WseF5x1oAwEEO8g\"},\"zs\":\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcRGG_A_I5lQPkkqg2lMDbGh7oAoia7By2jhoHgJGox0\\u0026s\\u003d10\"}],[\"&#29483;&#21674;\",46,[512],{\"lm\":[],\"zh\":\"&#29483;&#21674;\",\"zi\":\"&#35987; \\u2014 &#21205;&#29289;\",\"zp\":{\"gs_ssp\":\"eJzj4tDP1TcwrCyqMGD0Ynves_rppFUAOMQHYg\"},\"zs\":\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcSQAMEz7n5AwO0o3jxemIZ42sRhDthz6T3rWt_HeYDP\\u0026s\\u003d10\"}],[\"&#29483;&#21674;app\",0,[512]],[\"&#29483;&#21674;&#23448;&#32593;\",0,[512]],[\"&#29483;&#21674;&#25104;&#20154;\",0,[512]],[\"&#29483;&#21674;app&#23448;&#32593;\",0,[512]],[\"&#29483;&#21674;&#22823;&#25136;&#29229; &#35282;&#33394;\",0,[512]],[\"&#29483;&#21674;&#27927;&#28577;\",0,[512]],[\"&#29483;&#21674;&#36393;&#22902;\",0,[512]],[\"&#29483;&#21674;&#23637;\",0,[512]]],{\"ag\":{\"a\":{\"40024\":[\"\",\"\",1,20]}},\"k\":1,\"q\":\"3e-YKkbWWUV1uyIpaIe2ORxb5OE\"}]"

        val sss = SearchTipUtils.parseSearchTip(ss)
    }
}