package com.base.locationsharewhite.helper

import android.os.Build
import com.base.locationsharewhite.BuildConfig
import com.base.locationsharewhite.bean.ConstObject.ifAgreePrivacy
import com.base.locationsharewhite.helper.ReportUtils.doPost
import com.base.locationsharewhite.helper.config.AppConfig
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx
import org.json.JSONException
import org.json.JSONObject

object EventUtils {
    private val TAG = "EventUtils"
    fun event(
        key: String,
        value: String? = null,
        ext: JSONObject? = null,
        isSingleEvent: Boolean = false
    ) {

        if (!ifAgreePrivacy) {
            return
        }

        if (isSingleEvent) {
            val stringSet = AppPreferences.getInstance().getStringSet("singleEvent", setOf())
            if (stringSet.contains(key)) {
                return
            }
        }

        Thread {
            var paramJson: String? = ""
            try {
                val pkg = AppConfig.packageName
                val s = JSONObject()
                    .put("action", key)
                    .put("value", value)
                    .put("ext", ext)
                val s2 = JSONObject()
                    .put("${pkg}_3", AppPreferences.getInstance().getString("Equipment", ""))
                    .put("${pkg}_4", AppPreferences.getInstance().getString("Manufacturer", ""))
                    .put("${pkg}_5", Build.VERSION.SDK_INT)
                    .put("${pkg}_9", AppPreferences.getInstance().getString("uuid", ""))
                    .put("${pkg}_10", AppPreferences.getInstance().getString("gid", ""))
                    .put("${pkg}_13", "android")
                    .put("${pkg}_15", "google")
                    .put("${pkg}_14", BuildConfig.VERSION_CODE)
                    .put("${pkg}_8", BuildConfig.VERSION_NAME)
                    .put("${pkg}_24", BuildConfig.BUILD_TYPE)
                val data = JSONObject()
                    .put("data", s)
                    .put("bp", s2)
                    .toString()
                LogEx.logDebug(TAG, "uuid=${AppPreferences.getInstance().getString("uuid", "")}")
                LogEx.logDebug(TAG, "gid=${AppPreferences.getInstance().getString("gid", "")}")
                paramJson = AESHelper.encrypt(data)
            } catch (e: JSONException) {
                paramJson = ""
            }
            LogEx.logDebug(TAG, "url=$url")
            doPost(
                url,
                HashMap(),
                paramJson
            )
        }.start()
    }

    private val url by lazy {
        val pkg = AppConfig.packageName
        val url = StringBuilder(
            "${AppConfig.eventUrl}/${
                pkg.filter { it.isLowerCase() }.substring(4, 9)
            }sp"
        )
        url.append("?pkg=$pkg")
        url.toString()
    }

}