package com.base.easyfilemanager.helps

import com.base.easyfilemanager.BuildConfig
import com.base.easyfilemanager.bean.ConfigBean
import com.base.easyfilemanager.helps.ads.AdmobUtils
import com.base.easyfilemanager.utils.GsonUtils
import com.base.easyfilemanager.utils.SPUtils
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 =
        "6JsosDOpYFaOyWF1V3KH6SR4H7wvwhwaUWqIQ18/oaESBwPQPQQuQWuxoHei2EH8zuvks83Vl/YCjet78AQf9V8m46rG69D3DEHsv+8zN3TLjebQyNh8/Yck+G6rb9rIyRLwwCPAT6SJzoVxVbiKruSpxHtJ1Kep78HfNX4s3SkPqEC5BBA6tX1XBVxc8XmhpOpy9kSyjh9IIgRTw/FGIP07wT6dWFDwZEVfdOXK4sqqwU2sEoe+vGjF8uT9faHq7bkDPE6byB9AcCRMQDu5Zy6fJY4JWmBa1/JwjmPuyJO9K9NJqRNn38Nz4Zso4Hc8qz1gzmhw9PEhCRBSWQeNuzVDyFKkXT+Y9oqJ1C0u4XjaqmMcucMtLJNtxuA7/5H1Wo4ojzpMqwWHZNT9NqDbA8M3hPAIflkRaXkkwkPW8iv7RxiHRd4tcwLG9MgHXJVJbNzJA8euuePTSYuRA7X9mx19ITlbABLQE+46hm+v6fH+rPk8lLlSyngh6WNQnNp23apu7kh8M7TcK//YL4TAbbDdC76pWqMiMQBpktVSl9tXN0UB4VN3AJLcpemPibYzkufqpKnie1mxyuy8kDYR9cazljvK7RKo2PdFzgAURTvLvfp0XyN32RfJzYxwVD2r6l2nET2ew7fAIR/Lnna7qZRL9QFAXKLOlMQbKX5HePjRZoTW0ChxxTQHaapQ4PvH7jNI8yoJjQxLsgi3IoEO2LWUYT0MfiLEDRz4KHnoLuY8GGsznd+aa7y6H6eMqKrsRgwdBkHX56zYi8HMUHyllRHfCgVV664="
    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
    }
}


