package com.zxhyis.toolss.ad

import android.app.ActivityManager
import android.content.Context
import android.os.Process
import android.text.TextUtils
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.blankj.utilcode.util.GsonUtils
import com.zxhyis.toolss.BuildConfig
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.ad.bean.AdUnitCfg
import com.zxhyis.toolss.ad.bean.AdsCfg
import com.zxhyis.toolss.ad.bean.ConfigureData
import com.zxhyis.toolss.ad.bean.GlobalConfig
import com.zxhyis.toolss.ad.bean.PushCfg
import com.zxhyis.toolss.ad.bean.PushManagement
import com.zxhyis.toolss.logic.testLog
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


object ComUtils {
    private val TAG = "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 {

    }

    fun requestCfg() {
        //获取接口配置
        //将获取到的json string 存储到sp中。
        testLog("requestCfg")
        if (TextUtils.isEmpty(FileApp.fContext.queryDataStoreBlock(INSTALL_INFO, ""))) {
            val referrerClient = InstallReferrerClient.newBuilder(FileApp.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)
                                EventHelper.event("install_referrer", ext = obj)
                                MainScope().launch {
                                    FileApp.fContext.saveDataStore(
                                        INSTALL_INFO,
                                        response.installReferrer
                                    )
                                }

                                //调用接口请求

                            }

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


                            }
                        }
                    } catch (_: Exception) {
                        EventHelper.event("install_referrer_error", isSingleEvent = true)
                    }

                }

                override fun onInstallReferrerServiceDisconnected() {

                }
            })
        }

        if (isUpdateConfig()) {
            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).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 {
                        val i = Regex("\"data\":\"(.*?)\"").find(it)
                        if (i.toString() != "null") {
                            i!!.groupValues[1].let {
                                val str = AESHelper.decrypt(it)
                                FileApp.fContext.saveDataStoreBlock(getStringKey("comConfig"), str)
                                FileApp.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 {
        val str = FileApp.fContext.queryDataStoreBlock(getStringKey("comConfig"), "")
        val defaultStr = AESHelper.decrypt(
            " "
        )

        if (TextUtils.isEmpty(str)) {
            return defaultStr
        }
        if (BuildConfig.DEBUG) {
            return defaultStr
        } else {
            return str
        }

    }

    fun isUpdateConfig(): Boolean {
        //
        val time = FileApp.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
    }

}