package incredibleic.guffawic

import android.os.Build
import com.easy.clean.BuildConfig
import tooic.fatalityic.Runawayic.ifAgreePrivacy
import tooic.fatalityic.GlobalConfig
import incredibleic.guffawic.Propagationic.doPost
import tooic.fatalityic.redic.speckledic.hankeringic.Farawayic
import tooic.fatalityic.redic.speckledic.hankeringic.Upholsteryic
import org.json.JSONException
import org.json.JSONObject
import java.util.TimeZone

object Glowwormic {
    private val TAG = "EventUtils"


    fun event(
        key: String,
        value: String? = null,
        ext: JSONObject? = null,
    ) {

        if (!ifAgreePrivacy) {
            return
        }

        Thread {
            var paramJson: String? = ""
            try {
                val pkg = GlobalConfig.PACKAGE_NAME
                val s = JSONObject()
                    .put("action", key)
                    .put("value", value)
                    .put("ext", ext)
                val s2 = JSONObject()
                    .put("${pkg}_3", Farawayic.getInstance().getString("Equipment", ""))
                    .put("${pkg}_4", Farawayic.getInstance().getString("Manufacturer", ""))
                    .put("${pkg}_5", Build.VERSION.SDK_INT)
                    .put("${pkg}_9", Farawayic.getInstance().getString("uuid", ""))
                    .put("${pkg}_10", Farawayic.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)
                    .put("${pkg}_34", TimeZone.getDefault().getID())

                val data = JSONObject()
                    .put("data", s)
                    .put("bp", s2)
                    .toString()
                Upholsteryic.logDebug(TAG, "uuid=${Farawayic.getInstance().getString("uuid", "")}")
                Upholsteryic.logDebug(TAG, "gid=${Farawayic.getInstance().getString("gid", "")}")
                paramJson = Indirectlyic.encrypt(data)
            } catch (e: JSONException) {
                paramJson = ""
            }
            Upholsteryic.logDebug(TAG, "url=$url")
            doPost(
                url,
                HashMap(),
                paramJson
            )
        }.start()
    }

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

}