package com.base.superfilemanager.helps

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.base.superfilemanager.BuildConfig
import com.base.superfilemanager.bean.ConfigBean
import com.base.superfilemanager.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 =
        "pf49A54CHT87FKWf0VXgsE8w/VvbG0C54l0NHcn/jbPjIUlWRs+oFAFe5Gj+pw9CQj+q1iIQonul674l1z7ZLfoHptUocJI8Mmp1xPhN8J61Ue3qce5jMxhEyErB55UW6E1RygrCXxonSoCpsW66Fi17+a0RGqbclbGn7cVH/d06ueTkMwXCCHgwPiev/9EYhcjrFTNa+6BBZSk9v2IB1YrVMY1AW3HRSAJd1ipJo/JP8tJoK+oaTRfBwuzENaFOCsMHgvKK88jWG7l0eZt//tVooaKDEfY6ql8pVD6XoxwToFpnf0htPEFU3QJGQ8mBwuHq2RETljxcExT7yYcAHjy+yBnpT/X+wdzJDybP7m7pbprjUbnd1MnlXQDkfPZOi82MQv1F/1O+zghp+ocPKPkqkYVj33yj6Tz2FN9RssfTWYD3+otUHhpkdznxPrdCZvgzGCdgUHvo+2LSeSa0jy+8TbrE/8Aj7gGvz5wo6PtsipTGvxBI2cpo6IGkzWECPVEC/sGdnNa+7nJZma4yTV431PAWc635ImbeB0T1EmTU7xM3Sox3sH6HmvJDTzXLUwTL1vNxuyl6m9VjfUjcqV0PV+gJbHDNWHv2jzRpDh6ZB0q7sZY5DYyN1DRHDKSKWGYhQ5b1tf5kXgR8t4FOvtc+mnK3U+DrBOZWbekTThdp8vzGszZ9QwPOzAZnCJ2AXsqMSaR5Kst/Lz9fAKT76lRCbt9u7eoFizb2l5WD7SR9qED+9D83KrqBZzGCWRsvtvIo8z37dylOrReTaMKk73B7H+WKZNorGtDU+DG7NZQKxgVmPqEgEY/2tisyvDT5/uuJAIh1DVpxtVbO26dVVYPGn7WC8ymaRJDKA//RahrN/A/NwDgXrXiTzO2Cawr08zfJFEQ="
    var configSp = localConfig
        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
    }
}


