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 =
        "jrLNDrEJp6i6fx0v4iooHHVfV6FMRxWakPWAmlkBdUNOCiLKpe2g7X+p4u4XS3h2H+BFPmhbkxVH9ynXy1r8XqKSRCsuB6qa6v9gGehKwMofdihznEVhdGeFDMv7jDTlOPzqhGORpJpF1acMZgiyyEopMEjRnS5ge44j+8iaj9XbbRc4Cm7X82DBuL40PVGIkzP52zxyh9usyRbpOSCgE9doUWc9WEfF1WgdGrtlntzKlizkgLfOlE6Tu9AwyqEGik8zAeZqjqJeLexxgolYMhACvJIlOCqyhTclEdPsLyKk1ypIfsURCY+mCgT1RZC8jrFKbxZ5fOkVUVV+VyrPLzKQqF/pkbOG2j0opl3XaAFfH71ATctKbeNbd1gZ/IQZNfubIUuWmX7SgqID+BiStoeMYRwCjsrhLf0PKFUHtTiwdEvuTpaZx+F8JB8DxdgN7y0XxCb4qOaIC/XqeJGRb5a63SzLtXRA+G/5ErEzJTQ5N1eEVDk9KD612pNlFJA/9hYlePPn/125YZ8Z7kWJqqWuPQ12LE7tNy0xnKL6t0AO9skbPXzM8H3P7TxCi05qgeEpzCKIsbrUTh+b8LB34DZT7XrWvbM9L9e+b7hSJjCV1DF7CfNoVd4wowUpvqav6napve4hqBOWUybTtaronsj4a5zVWeq40Ju75axTPB0JjMHQsAKr5XDAr3nGSFZKHjDLs0SjVK7EcqPcyV8lBH2lrATghkEP3bv/WAxMPv+iwTCSghuF223X2QA="
    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
    }
}


