package com.base.filerecoveryrecyclebin.utils

import android.util.Log
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.bean.ConfigBean
import com.base.filerecoveryrecyclebin.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 java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale

object 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())
        "$API_URL/${appCode}spk?pkg=$packageName&source=channel"
    }

    //origin user = only pick &source=origin
    private fun getOriginUrl(): String {
        val packageName = ConfigHelper.packageName
        val appCode = packageName.substringAfter(PACKAGE_NAME_PREFIX).take(5).toLowerCase(Locale.getDefault())
        return "$API_URL/${appCode}spk?pkg=$packageName&source=origin"
    }

    fun requestCfg(callback: (ConfigBean?) -> Unit) {
        CoroutineScope(Dispatchers.IO).launch {
            val response = doGet()
            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 = if (originFlag) getOriginUrl() else 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)

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

        AdDisplayUtils.getInstance().saveSp()
    }
}

