package com.test.basd.onecleanmaster.helps

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.test.basd.onecleanmaster.BuildConfig
import com.test.basd.onecleanmaster.bean.ConfigBean
import com.test.basd.onecleanmaster.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 =
        "tof3i6zlAWYcy0tC3tJRNJdqkHY0pdrGpt+pz3sMloYhY0sQCyRzHHZ8s4mz6o4vMGsUTi1++OSCnhZSSCXhE6j6GbR93dyZyQWh37nrFEWcsbmYUnvyfnd0/aY0JEmePH1iB/nluACG9rV/qgk+Cz2GNs/hpi6DEhUvlsKYFE3+gb4g2LRjhO49os0Q/IlsYN5GWskjTWAlNlgbT3L84VoIpLoliKGMaDCiUhnM3A7yxpaOXm1MN39hp6cG4c/Q2VhltW2V6cAKdPOd0A1jDAbAkhX1cRQ8g4JzMxuMOzgqMwqZ0FSB/p+udDakTxGb8FH7W0NRBWCukMWvSGK1SUDNJI/IEIcq9RAegSlW6TpKy2dqXVWfND3/AvD7eLGM3tnNAdoU8BHN31AIQOIjaZQD5GVf1BtVmCaIVm1gVK2tNI06iqEFO1Zii7/f4lyoJOYbv5lGsC5NgFDEnZthaJWfplG5F1p9oskHEeS3+DpVyPNdYbzWuVVLq0G4STAJzk3pp8JJ0ZKgzekz6wo56hRKfxIykAOvyMhdRtrTvBDty0+Eza0SjdITg9EqoW26ldfDasfB1Y256UeWgpbxVgDaCCtXYg18dBJavETGLg3z1BFsDzq+PAXE3htLwHIk8NIFIvUBnyDDlpHAtCufEvsH5iHfEG87CID/5UtUsxvT6nRceBKXqsac08ZjHNTBKlTVe3xcN/gCnHFpcIEsKYvcV/CXo+5vSSidrzeMdfJApCpDZr4+S2KgiXGSOap03fOhgOCxo2yA/ja0HLjnyP6aeb2swLXYj0fNEOxu4PUcdPXAcvsZ5B0H1cOfFHXNOvZ0UjyC6wLJbZ3cBCXbWW8yRfgYSihL6NONspnMe1EB+9idJPto6PKqLgXyRfwZ4NnFDssMxdTeLT0RitR52aLiC8lRe9nEjxMkrz/95LRg7f/8DCz9CHcYak5dL9PPR9ckC3E6NjFMPW6uLcjuFYg4EO8qVpEp4BUbVbVHsr7JYR6pF8KR0cjQlotlLBCd9g04ax/v6vqKZrBH2CscoR+vjgiFcBEidXB1CfBIJ3IwCvcwJr8nEp+urLQ531yG+ajdr2nh7AJxbtK10rKX36YbI93awdEwXcUWPe/kpJkV6cXaNDyXTo8V5c0uqf3wZ5Zu/8vIgNVOfHMkB/YaRVX3JZ5E7StcCXXRxvoi1VgOUp/HbpV3Xv9lYvHT76S7KWVDRwvgMNDsc6SSKmLKjWWrZRW6GDNbMySn+keSehJxNhEn+D0lpuLbbJbcmvf17Kct3U9XKRxYkjdkZCx0VsV9BsUipk/f1YQ7rPZDRJNCMjjDKM2xEvsp32VI4u7yk+LS"

    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
        SPUtils.getInstance().put("loading_page_time", configBean.open_time_out)
        LogEx.logDebug(TAG, "Sp configBean=$configBean")
        return configBean
    }
}


