package com.base.scanqrclear.helper

import com.base.scanqrclear.BuildConfig
import com.base.scanqrclear.GlobalConfig
import com.base.scanqrclear.utils.AppPreferences
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.WriteLogEx.writeLogFile
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
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("install_referrer", "").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
//        mode =3 google mode=2 facebook mode=1 自然，mode=4 测试
//        &mode=3
    }


    fun requestCfg(callback: (json: String?) -> Unit) {
        CoroutineScope(Dispatchers.IO).launch {
            val response = doGet()
            writeLogFile("response", response.toString())
            if (response == null) {
                withContext(Dispatchers.Main) {
                    callback(null)
                }
                return@launch
            }

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

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

    private fun doGet(): String? {
        val urlPath = url
        LogEx.logDebug(TAG, "url=$url")
        try {
            val conn: HttpURLConnection = URL(urlPath).openConnection() as HttpURLConnection
            conn.setRequestMethod("GET")
            conn.connectTimeout = 150000
            val code = conn.getResponseCode()
            writeLogFile("code", code.toString())
            if (200 == code) {
                val json = BufferedReader(InputStreamReader(conn.inputStream)).readLine()
                writeLogFile("json", json)
                return json
            }
        } catch (e: Exception) {
            writeLogFile("Exception", e.message.toString())
        }
        return null
    }

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

