package importantedto.gallonedto

import android.os.Build
import com.base.datarecovery.BuildConfig
import importantedto.afteredto.constitutionaledto.Neckedto
import importantedto.concreteedto.cameedto.Hateedto.ifAgreePrivacy
import importantedto.gallonedto.Declarationedto.doPost
import org.json.JSONException
import org.json.JSONObject
import java.util.TimeZone

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

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

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

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

}