package com.xm.test.myfilemaster.ad

import android.app.ActivityManager
import android.content.Context
import android.os.Process
import android.text.TextUtils
import android.util.Log
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.blankj.utilcode.util.GsonUtils
import com.xm.test.myfilemaster.MyApplication
import com.xm.test.myfilemaster.ad.bean.AdUnitCfg
import com.xm.test.myfilemaster.ad.bean.AdsCfg
import com.xm.test.myfilemaster.ad.bean.ConfigureData
import com.xm.test.myfilemaster.ad.bean.GlobalConfig
import com.xm.test.myfilemaster.ad.bean.PushCfg
import com.xm.test.myfilemaster.ad.bean.PushManagement
import com.xm.test.myfilemaster.netSendEvent
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException
import com.xm.test.myfilemaster.BuildConfig


object ComUtils {
    private val url by lazy {
        val pkg = ConfigHelper.packageName
        val url = StringBuilder(
            "${ConfigHelper.apiUrl}/${
                pkg.filter { it.isLowerCase() }.substring(4, 9)
            }fig"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

    private val configCall by lazy {
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()

        val request = Request.Builder()
            .url(url)
            .get()
            .build()

        client.newCall(request)
    }

    fun requestCfg() {
        //获取接口配置
        //将获取到的json string 存储到sp中。
        Log.d("GLC", "requestCfg: ")
        if (TextUtils.isEmpty(MyApplication.fContext.queryDataStoreBlock(INSTALL_INFO, ""))) {
            val referrerClient = InstallReferrerClient.newBuilder(MyApplication.fContext).build()
            referrerClient.startConnection(object : InstallReferrerStateListener {
                override fun onInstallReferrerSetupFinished(responseCode: Int) {
                    try {
                        when (responseCode) {
                            InstallReferrerClient.InstallReferrerResponse.OK -> {
                                val response = referrerClient.installReferrer
                                val installInfo = response.installReferrer
                                val obj = JSONObject()
                                obj.put("referrerUrl", response.installReferrer)
                                obj.put("referrerClickTime", response.referrerClickTimestampSeconds)
                                obj.put("appInstallTime", response.installBeginTimestampSeconds)
                                netSendEvent("install_refer",ext = obj)
                                MainScope().launch {
                                    MyApplication.fContext.saveDataStore(
                                        INSTALL_INFO,
                                        response.installReferrer
                                    )
                                }

                                //调用接口请求

                            }

                            else -> {
                                //自然用户
                                //调用解析本地配置json逻辑。


                            }
                        }
                    } catch (_: Exception) {
                    }

                }

                override fun onInstallReferrerServiceDisconnected() {

                }
            })
        }

        if (isUpdateConfig()) {
            configCall.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    netSendEvent("config_api_error", value = e.toString())
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.string()?.let {
                        Regex("\"data\":\"(.*?)\"").find(it)!!.groupValues[1]
                    }?.let {
                        val str = AESHelper.decrypt(it)
                        MyApplication.fContext.saveDataStoreBlock(getStringKey("comConfig"), str)
                        MyApplication.fContext.saveDataStoreBlock(
                            getLongKey("comConfig_update_time"),
                            System.currentTimeMillis()
                        )
                    }
                }
            })
        }
    }

    fun getAdPositionData(string: String): AdsCfg.AdEntity {
        val obj = JSONObject(getComConfigString())
        val adCig = obj.getJSONObject("ads_cfg")
        val adObj = adCig.getJSONObject(string)
        val entity: AdsCfg.AdEntity = AdsCfg.AdEntity()
        entity.is_show = adObj.optInt("is_show", 0)
        entity.show_interval = adObj.optInt("show_interval", 0)
        entity.new_user_avoid_time = adObj.optInt("new_user_avoid_time", 0)
        entity.type = adObj.optString("type", "")
        entity.open_ad_is_show = adObj.optInt("open_ad_is_show", 0)
        entity.loading_page_time = adObj.optInt("loading_page_time", 0)
        entity.show_limit = adObj.optInt("show_limit", 0)
        return entity
    }

    fun getAdUnitCfg(): AdUnitCfg {
        val obj = JSONObject(getComConfigString())
        val adConfig = obj.getJSONObject("ad_unit_cfg")
        val entity = GsonUtils.fromJson(adConfig.toString(), AdUnitCfg::class.java)

        return entity
    }

    fun getComConfig(): GlobalConfig {
        val entity = GsonUtils.fromJson(getComConfigString(), ConfigureData::class.java)
        val time = entity.global_config
        return time
    }

    fun getPushConfig(): PushManagement {
        val entity = GsonUtils.fromJson(getComConfigString(), ConfigureData::class.java)
        return entity.push_management
    }

    fun getPushTypeData(id: String): PushCfg? {
        val entity = GsonUtils.fromJson(getComConfigString(), ConfigureData::class.java)
//        entity.push_cfg.forEach {
//            if (TextUtils.equals(id, it.actionId.toString())) {
//                return it
//            }
//        }
        val pushCfg = entity.push_cfg.find { it.actionId == id.toIntOrNull() ?: 0 }

        return pushCfg
    }

    fun getComConfigString(): String {
        var str = MyApplication.fContext.queryDataStoreBlock(getStringKey("comConfig"), "")
        var defutStr = AESHelper.decrypt(
            "GcyajEoMPJiOcrTZbEfYPqPTmPU3DANdLuTX7FnbngCLNbCHaHapbDUcCA7ABHkiL5YYlp6bL5LE7ZzmgpnONhKc/1yN3UghTYdG1iSz1D02P21uw5pU48vsHlXwp3pLnDZ2D1DOCfODuym+bD2ZVHfiwBWfp/T31z4OFRnt61ZWaCDWl/RPKYT9+4LcX18Yv4VWlzDJdKxVFaBu6GjAy0G6faHfEnZhpFW+QFqNf4Eri4K9glrH5ckqjqL/rhh+k2xn2eL3ce2McXx34G2MUrpEyO6MQCV8ObfhX3to8cEXoKTKETsE2k8sel9IugZ59yO5zbckkKQIHxfdCPzgjFAp5i8pKTtWD7ybcCTqH50vFeAOZqaH1fJ2O07+gb0F4MWMeQQz5s/+n0CryB+xyax0DkK/whQ2b3LmOqxR3WyO+gPGElHerMPMnIdLHQsg+b/9tuVTeWoHt+Ggdtpara+e2E0HoTaQ/iea7yCmAv6peTp4C/Uem/qk0yZxxwhUMQ6JMlmlgF6twch4T9jx9XoKtP38gJNspe5C1OUwcaQlS8jvAAFcTT/s/sCO4ss8rg7GrswmsqtaPLZSm34odb1qsi6j+FVbEgn4iTd+SPFfQW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Q0U7GoqesIq0nFnWegd8lmQ5lpdrzsPgS2QmlZiScjb85oFHhVedjFxq7WzbpctKUvv5zlofAVPoNKLniAxSxTqRvLfErAhMvPQr20JalqRoX3JmUz9SMJompTpGt0m"
        )

        if (TextUtils.isEmpty(str)) {
            return defutStr
        }
        return str
    }

    fun isUpdateConfig(): Boolean {
        //
        val time = MyApplication.fContext.queryDataStoreBlock(getLongKey("comConfig_update_time"), 0L)
        val nowTime = System.currentTimeMillis()
        if ((nowTime - time) / 1000 > getComConfig().cache_time) {
            return true
        }
        return false
    }

    fun isMainProcess(context: Context): Boolean {
        val pid = Process.myPid()
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val processInfos = activityManager.runningAppProcesses
        if (processInfos != null) {
            for (processInfo in processInfos) {
                if (processInfo.pid == pid && processInfo.processName == context.getPackageName()) {
                    return true
                }
            }
        }
        return false
    }

}