package com.test.basd.supercleanermax.helps

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.test.basd.supercleanermax.BuildConfig
import com.test.basd.supercleanermax.bean.ConfigBean
import com.test.basd.supercleanermax.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 =
        "Fe5MEzroM+pCsdsxsLTeUuf7TT5rSM/fOu7xNx5OHfER6Ekm55d6hwrdViuDLK+9+vgB80XMIyb1opNBWRJT5RogMNTdVVkdAAiOGH0WsqZ3zRVyB4lvv4fHKspSJiYEU7bMWtufqGzYML8BMGACAZda80N/0onj7K0gKsV3qnm20QZheQDpg1DKwZQuNDUKDmYbe4QilwTq5r9bLAtXWLNJMuJxd5a0kh9Mdn7q1W1Isd7VVbHfVKtUDoCNPy5tgGgSbAR90niXnh2wwHkFzybAl0xPaEy8tuqmhN91skv27gHODzweQoLH1U5jq8Hux79Sqnr9aTXnOAy3ogFGbPijim1J1H5jl6lqcH0x2KDTrQ6jrQTq1IwKlnKih4hYZPf9G/A4MVOB4ZS+KwrSsGzDGioc25mFm43jSeqp6VgKXV7jrA3E5xK9pUPkxIkaWIxHyrtuWx8xvd0j04XWBIQ+NgyToGJ/ooelKCzT/Bz0Cyz9t7P3b3Qr6ij8G5Y594fM3v1HhHoGeWdYGSS6oWLfoyVOKFpvT78BzVmLjsTcou+i+fOlXl0DmLGk/BH2Rk0p0gzI3FYeA2rH9pUCAhMgaK3+O3N6pu8HM/vmhGkjHnQHQzOx+uhWGqjxbhZgSKVMkwaDnSSZX/ndt8Rge15ktjeKHs9mv0MgQjvda/vnnqdovGlf56lKGnTIlQ7Sk11H/0jiwmDmjge8L4bO+xeKUMRSXFJejTIutGn18Z8pB3khj5fEJQLklUA="
    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
    }
}


