package com.base.filerecoveryrecyclebin.help

import android.util.Log
import com.base.filerecoveryrecyclebin.BuildConfig
import com.base.filerecoveryrecyclebin.GlobalConfig
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.bean.ConfigBean
import com.base.filerecoveryrecyclebin.utils.AESHelper
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale

object NewComUtils {

    private val TAG = "NewComUtils"
    private const val API_URL = GlobalConfig.URL_API
    private const val PACKAGE_NAME_PREFIX = GlobalConfig.PACKAGE_NAME
    private const val DATA_KEY = "data"

    private val url: String by lazy {

        val packageName = GlobalConfig.PACKAGE_NAME
        val appCode = packageName.substringAfter(PACKAGE_NAME_PREFIX).take(5).toLowerCase(Locale.getDefault())

        val bRefer = android.util.Base64.encodeToString(
            AppPreferences.getInstance().getString("referrerUrl", "").toByteArray(),
            android.util.Base64.DEFAULT
        )

        var s =
            "$API_URL/${appCode}spk?pkg=$packageName&referrer=${bRefer}&vn=${BuildConfig.VERSION_NAME}&vc=${BuildConfig.VERSION_CODE}&device=${
                AppPreferences.getInstance().getString("gid", "")
            }&aid=${AppPreferences.getInstance().getString("uuid", "")}"

        if (BuildConfig.DEBUG) {
            s = "$s&mode=4"
        }

        s
    }

    fun requestCfg(callback: (ConfigBean?) -> Unit) {
        LogEx.logDebug(TAG, "requestCfg")
        MainScope().launch(CoroutineExceptionHandler { _, _ -> } + Dispatchers.IO) {
            val response = doGet()
            LogEx.logDebug(TAG, "response=$response")
            if (response == null) {
                withContext(Dispatchers.Main) {
                    callback(null)
                }
                return@launch
            }

            val data = extractData(response)
            if (data == null) {
                withContext(Dispatchers.Main) {
                    callback(null)
                }
                return@launch
            }

            val decryptedData = AESHelper.decrypt(data)
            parseConfigBean(decryptedData)
            withContext(Dispatchers.Main) {
                callback(null)
            }
        }
    }

    private fun doGet(): String? {
        // val originFlag = AppPreferences.getInstance().getString("install_source", "") == "origin"
        val urlPath = url
        Log.d("okhttp", urlPath)
        try {
            val conn: HttpURLConnection = URL(urlPath).openConnection() as HttpURLConnection
            conn.setRequestMethod("GET")
            conn.connectTimeout = 150000
            if (200 == conn.getResponseCode()) {
                val json = BufferedReader(InputStreamReader(conn.getInputStream())).readLine()
                Log.d("okhttp", json)
                return json
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("okhttp", e.toString())
        }
        return null
    }

    private fun extractData(response: String): String? {
        val regex = Regex("\"$DATA_KEY\":\"(.*?)\"")
        val match = regex.find(response)
        return match?.groupValues?.get(1)
    }

    private fun parseConfigBean(json: String) {
        Log.d("okhttp", json)
        val gson = Gson()
        val type = object : TypeToken<Map<String, String>>() {}.type
        val configMap = gson.fromJson<Map<String, String>>(json, type)
        try {
            configMap.forEach { t, u ->
                // 对于整型值使用parseInt, 长整型使用parseLong
                AppPreferences.getInstance().put(t, u)
                LogEx.logDebug(TAG, "t=$t u=$u")
            }
        } catch (_: Exception) {

        }


        val jsonObject = JSONObject()
        jsonObject.put("ut", AppPreferences.getInstance().getString("ut", ""))
        EventUtils.event("user_type", ext = jsonObject)

        AdDisplayUtils.getInstance().saveSp()
    }
}

