package com.test.basd.supercleanermax.helps

import android.os.Build
import android.util.Log
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import com.test.basd.supercleanermax.BuildConfig
import com.test.basd.supercleanermax.helps.ConfigHelper.ifAgreePrivacy
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException

object EventHelper {

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

    fun event(
        key: String,
        value: String? = null,
        ext: JSONObject? = null,
        isSingleEvent: Boolean = false
    ) {
        if (!ifAgreePrivacy) {
            Log.e(TAG, "ifAgreePrivacy=$ifAgreePrivacy")
            return
        }

        if (isSingleEvent) {
            val stringSet = SPUtils.getInstance().getStringSet("singleEvent")
            if (stringSet.contains(key)) {
                return
            }
        }
        val pkg = AppUtils.getAppPackageName()
        val s = JSONObject()
            .put("action", key)
            .put("value", value)
            .put("ext", ext)
        val s2 = JSONObject()
            .put("${pkg}_1", "${ScreenUtils.getScreenHeight()}")
            .put("${pkg}_2", "${ScreenUtils.getScreenWidth()}")
            .put("${pkg}_3", DeviceUtils.getModel())
            .put("${pkg}_4", Build.MANUFACTURER)
            .put("${pkg}_5", Build.VERSION.SDK_INT)
            .put("${pkg}_8", AppUtils.getAppVersionName())
            .put("${pkg}_9", DeviceUtils.getAndroidID())
            .put("${pkg}_10", ConfigHelper.gid)
            .put("${pkg}_11", System.getProperty("http.agent"))
            .put("${pkg}_13", "android")
            .put("${pkg}_14", "${AppUtils.getAppVersionCode()}")
            .put("${pkg}_15", "google")
            .put("${pkg}_24", BuildConfig.BUILD_TYPE)
        val data = JSONObject()
            .put("data", s)
            .put("bp", s2)
            .toString()
        val body = AESHelper.encrypt(data)
            .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
        val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
            }
        }.build()

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("TAG", "event: $key")
                if (isSingleEvent) {
                    val stringSet =
                        SPUtils.getInstance().getStringSet("singleEvent", mutableSetOf())
                    stringSet.add(key)
                    SPUtils.getInstance().put("singleEvent", stringSet)
                }
            }
        })
    }
}