package com.test.basd.smartjunkcleaner.helps

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.test.basd.smartjunkcleaner.BuildConfig
import com.test.basd.smartjunkcleaner.bean.ConfigBean
import com.test.basd.smartjunkcleaner.helps.ads.AdmobUtils
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException


object ComUtils {
    private val TAG = "ComUtils"

    val localConfig =
        "YilhIWGhy8GIPCf7wd7VebbfVaiFlMRQJNZ4xlAJxKQRi8q78bnvxrXncebtqhyOIBQVG2j1uQRLd0hTJnZJvcoM+UDEsXBTzIBN4rDRTpxwxIHkhhGQ3aFVy8FdRlE2GQgwjl6inZDPVxV5lGeE2PwU0x60ZzAXjs3hzfHT90I/kA11d052vySNBj9Awsgip6KfIsMIS7PpR9XDocJhspEzd0yj6Wr5H47L3rscYXfX/lf3auzuOMDy0M5hZB7JwuKBQRV82fai11t7Bo1cDQNpZTUuRXChg8gDOnJT5lrJYr7HnSAht1AixHxQj6PALJwNnE23fDc5JFPU8d/ddZC1TOQHrcxkmEbnZnVcf0BcjEqPiSHOcRrYqGiMxUzHtUZoSQ9SA30ASINuQC/QeGZscIa0tKMoxJRu6lnVh6rpoaxk5iO54X06ie5THgMHSjRJE2TgsTrCP1B938uNS5JgJ2Z9iCBl9/PZDAQ+Yh9uzkfM0p+/zdg8UtQlJZreDG63hK+AXioe4ct8piCTiE2gKr2lwsqqsISOh3TdNxxc9ElyK4V9sajxSwcj9X3jVOPIGl0L2K26aCWE9NeWUx791dG58bxlYfM/UI1cwdVSUqHtgbaQCG7lL2eV7Smlz45Z4y4U4dEyuVOgEeNMyVbj3N3S9WRt1768cbYeii6zWWnwPuVp1qN2HZUsW7EpnL5cWE7hx1K86e6UW13FaRrnRnjNgXHMDAtVG9BcgIWug1+HlnAHZdc="
    var configSp = ""
        get() {
            return SPUtils.getInstance().getString("configSp", field)
        }
        set(value) {
            field = value
            SPUtils.getInstance().put("configSp", value, true)
        }

    private val url by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/${
                pkg.filter { it.isLowerCase() }.substring(4, 9)
            }spk"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }


    fun requestCfg() {
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()
        LogEx.logDebug(TAG, "url=$url")
        val request = Request.Builder()
            .url(url)
            .get()
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                EventHelper.event("config_api_error", value = e.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.string()?.let {
                    LogEx.logDebug(TAG, "it=$it")

                    val i = Regex("\"data\":\"(.*?)\"").find(it)
                    if (i.toString() != "null") {
                        i!!.groupValues[1].let {
                            val str = AESHelper.decrypt(it)
                            LogEx.logDebug(TAG, "str=$str")
                            configSp = str
                        }
                    }
                }

            }
        })
    }

    fun getLocalConfigBean(): ConfigBean {
        val json = AESHelper.decrypt(localConfig)
        LogEx.logDebug(TAG, "Local json=$json")
        val configBean = GsonUtils.fromJson(json, ConfigBean::class.java)
        LogEx.logDebug(TAG, "Local configBean=$configBean")
        return configBean
    }

    fun getSpConfigBean(): ConfigBean {
        var configBean: ConfigBean? = null
        try {
            configBean = GsonUtils.fromJson(configSp, ConfigBean::class.java)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (configBean == null) {
                LogEx.logDebug(TAG, "Sp configBean=$configBean")
                configBean = getLocalConfigBean()
            }
        }
        AdmobUtils.adShowCount = configBean.inter_show_limit
        AdmobUtils.nativeAdShowCount = configBean.native_show_limit
        AdmobUtils.isNowPlayAd = configBean.isNowPlayAd
        SPUtils.getInstance().put("loading_page_time", configBean.open_time_out)
        LogEx.logDebug(TAG, "Sp configBean=$configBean")
        return configBean
    }
}


