package com.base.datarecovery.utils

import android.util.Log
import com.base.datarecovery.help.ConfigHelper
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.*

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"
    }

    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)
            val configBean = parseConfigBean(decryptedData)
            withContext(Dispatchers.Main) {
                callback(configBean)
            }
        }
    }

    private suspend fun doGet(): String? {
        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): ConfigBean? {
        val gson = Gson()
        val type = object : TypeToken<Map<String, Any>>() {}.type
        val configMap = gson.fromJson<Map<String, Any>>(json, type)
        return if (configMap != null) {
            ConfigBean(
                actionS = configMap["actionS"] as? String,
                open = configMap["open"] as? Boolean,
                // ... other properties
            )
        } else null
    }
}

data class ConfigBean(
    val actionS: String?,
    val open: Boolean?,
    // ... other properties
)