package com.base.datarecovery.utils

import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.base.datarecovery.BuildConfig
import com.base.datarecovery.ads.AdDisplayUtils
import com.base.datarecovery.bean.ConfigBean
import com.base.datarecovery.help.ConfigHelper
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
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.Base64
import java.util.Locale

object NewComUtils {
    private val TAG = "NewComUtils"
    private const val API_URL = ConfigHelper.apiUrl
    private const val PACKAGE_NAME_PREFIX = ConfigHelper.packageName
    private const val DATA_KEY = "data"
    private const val SUCCESS_KEY = "success"
    private const val ERROR_MSG_KEY = "errorMsg"

    private val url: String by lazy {
        val packageName = ConfigHelper.packageName
        val appCode = packageName.substringAfter(PACKAGE_NAME_PREFIX).take(5).toLowerCase(Locale.getDefault())
        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
            val bRefer = Base64.getEncoder().encodeToString(AppPreferences.getInstance().getString("referrer", "").toByteArray())
            "$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", "")}"
        }else{
            "$API_URL/${appCode}spk?pkg=$packageName&vn=${BuildConfig.VERSION_NAME}&vc=${BuildConfig.VERSION_CODE}&device=${
                AppPreferences.getInstance().getString("gid", "")
            }&aid=${AppPreferences.getInstance().getString("uuid", "")}"
        }

    }

    fun requestCfg(callback: () -> Unit) {
        CoroutineScope(Dispatchers.IO).launch {
            val response = doGet()
            if (response == null) {
                withContext(Dispatchers.Main) {
                    callback()
                }
                return@launch
            }

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

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

    private fun doGet(): String? {
        val urlPath = url
        LogEx.logDebug("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()
                LogEx.logDebug("okhttp", json)
                return json
            }
        } catch (e: Exception) {
            e.printStackTrace()
            LogEx.logDebug("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)

        configMap.forEach { t, u ->
            // 对于整型值使用parseInt, 长整型使用parseLong
            LogEx.logDebug(TAG, "t=$t u=$u")
            AppPreferences.getInstance().put(t, u)
        }

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

        AdDisplayUtils.getInstance().saveSp()
    }
}

