package com.test.basd.cleanmaster.helps

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.test.basd.cleanmaster.BuildConfig
import com.test.basd.cleanmaster.bean.ConfigBean
import com.test.basd.cleanmaster.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 =
    "bJncEhOs3dOY2Pnsjh28rKzASWY6QmrTDdY5vo4iIdMq91zE4aqoHghp99DtAcA5v3Gxn0jYC3UsXbPjr8z3XxRCnpiL9KEEiLZbg05S2LFbx5nrugy/hho/pM9QbZNsT+pJyVQ47K1IgiV8+DXx/prWgzrVhK5Jxt5jp/oblg2BPZwy0B9CLbi9K1LNv3eu00TTyJoQTV7MsofMsdsooaSSUxNlVCEVCxPhWHx/75+P7282lqdFQzPT3RQtGrMGtvJKQEVY8TONLYVuGJtiZbAilzi3AA9NZ6nNFyMdGYCXNkkyRoKGFN9wld58ScLVadbzWgR37nVNEBq8LQfZPTpNH1Bo+BzVLHz0X8T4qBdWS1L3vkPBBD2vDCvTNkI8NPe6MQ69L0s2bRX8UAIH4ePai29vKG/wnOpPmVN0C6f/cr9lEu7u7KbVPzy4lvjDxb++Jtdv4mRKCPb65nEr2iCeTIa1ZCGQrBjV1nCFBYq5jNnVqrRtAANZz4MEC2hCkrvV7n3xFMZFQkvycwwdTYhfePs2+FifZyan8L2jCu4xD6wbx4jVGeAIZsdGeVQ4gixQCYmqm5HEdLWWR4fawPh8+zGmKbFHFO7R18rdCmv0ANUGcmq5y8qUlUvKthOrA97dd9IZv+yfh+3zWOjU2MhzbdfjsJP10EeeQ/41DyLn8WHJhBqx1ju9WDMNZAedra3biwSTwAn9S7yUwzh5uL1RpsPCX21QyzSuPBPZdZLKadQKf18Y9j1lGOTDGJBZLFLySGb/TWJignub9Y/0iGVwtg9csNJ/Er7oevwULVLOy3TCMlC2P4NoyK7gtVmWX8qeXCUI3cAN41D1vqi5Xscx3HkMxTUr8DDUO2alnzS2Xl5G4YaXUVDWmV8+lwivgEslryQ="
    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
    }
}


