package com.swiftcleaner.chovey.business

import android.util.Base64
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.swiftcleaner.chovey.BuildConfig
import com.swiftcleaner.chovey.GlobalConfig.KEY_GOOGLE_ADVERTISER_ID
import com.swiftcleaner.chovey.GlobalConfig.KEY_REFERRER
import com.swiftcleaner.chovey.GlobalConfig.KEY_UUID
import com.swiftcleaner.chovey.GlobalConfig.PACKAGE_NAME
import com.swiftcleaner.chovey.GlobalConfig.URL_API
import com.swiftcleaner.chovey.util.SPUtils
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException

object ConfigUtils {

    private val url by lazy {
        val url = StringBuilder("${URL_API}/${PACKAGE_NAME.filter { it.isLowerCase() }.substring(4, 9)}spk")
        url.append("?pkg=$PACKAGE_NAME")
        val referrer = SPUtils.getInstance().getString(KEY_REFERRER)
        url.append("&referrer=${Base64.encodeToString(referrer.toByteArray(), Base64.DEFAULT)}")
        url.append("&vn=${BuildConfig.VERSION_NAME}")
        url.append("&vc=${BuildConfig.VERSION_CODE}")
        url.append("&device=${SPUtils.getInstance().getString(KEY_GOOGLE_ADVERTISER_ID)}")
        url.append("&aid=${SPUtils.getInstance().getString(KEY_UUID)}")
        //打正式包注释掉 url.append("&mode=4")
        url.append("&mode=2")
        url.toString()
    }

    fun requestConfig(block: () -> Unit) {
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()
        val request = Request.Builder()
            .url(url)
            .get()
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                EventUtils.event("api_config_error", value = e.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let {
                    val result = Regex("\"data\":\"(.*?)\"").find(it)
                    if (result != null && result.toString() != "null") {
                        result.groupValues[1].let {
                            try {
                                val str = AESUtils.decrypt(it)
                                val gson = Gson()
                                val type = object : TypeToken<Map<String, Int>>() {}.type
                                val configMap = gson.fromJson<Map<String, Int>>(str, type)
                                configMap.forEach { (t, u) ->
                                    SPUtils.getInstance().put(t, u)
                                }
                                block.invoke()
                                val jsonObject = JSONObject()
                                jsonObject.put("ut",  SPUtils.getInstance().getInt("ut"))
                                EventUtils.event("user_type", ext = jsonObject)
                            } catch (_: Exception) {
                            }
                        }
                    }
                }

            }
        })
    }

}