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 =
        "UhvxWoalOdMvwDx3vyGjZJ5EyKhd/5zkB5gGx6KGZ+kAEYNveDTF9jJRaLfETaTWZ5AHXUR2j2tCyZYZVKaO1xct7mvbJsUylvG4IOURHq8/CoozWYpAShN2B9nPeJE6dcVfp36Squ4dHzwR/vzKXkoqNxiSYggCVOQtf3cPbWfF5ZXBGuRjZd3R33Rxp4DIvD6XrdxeCRyC+BorWaumngvq3EyV8ChiIazLe1NuWOSFOvQlE0iOjAMgYvu68bQ7t/7hdcvouzTQ8MfYaCM9J9nY1zHQRKasZs8YN+atgsfM57EnXzp+kfkKBYHi/Qgt4Z6HcM7H+IseSJEpFBEan3O3tHJRa5yzNvFwb7+zZDlUrXvv/UbYtUOFGxxY2VLuseqyXRFywHPqsLefSGV7ciB4+4h+ri3GSuSgRt7p/zLDBQcSbVT7IWNrNUW3iTczY+WdYWy7++FBsWx8J6NrhV4+UArqjcGXVm39JMBuxRUoO27KjHtGdx/X8XXKlelOpCAv0rYQbgAsdN/PyD7mzktUv+PncoyK6GT3uvjKhbTmxiPSaZ5Zae0Z0HjyrlNO7mXr5jBJRRMuQQYROZjwV/M/1H2xpF2tMoP5xramLv/QLgykJpZ6xRYSkXVQ4Y9ankFF5ZmarCq1JokCkINimhjD1QXPfli1+MNWRVNzJSekNJx8VFNCuYnH7c2rBIO7wGDfGigWGb3E6Qyb9aubLS6mJiBXzU42oJaiy/lxCTfGq3vCEeKNcILkM2DoAEL0vF4mNW+RP04RNwb7A+kUbhyjPw3CkUiTZPLqOigJaga5+IxSXTGqh2/EZ0UamvS3rl9Qj8Fy/Afe6Fi/aBag54kpMA6edthD7epNPU2dK+Sk6gdqtOd+Vx14f/mwtrC6Kx1JqAA="

    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
    }
}


