package com.tgv.malware.business.helper

import android.os.Build
import com.tgv.malware.BuildConfig
import com.tgv.malware.SpConstObject.ifAgreePrivacy
import com.tgv.malware.GlobalConfig
import com.tgv.malware.bean.config.ConfigBean
import com.tgv.malware.utils.AppPreferences
import com.tgv.malware.utils.LogEx
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
import java.util.TimeZone

object EventUtils {

    private val TAG = "EventUtils"

    private val client = OkHttpClient.Builder().apply {
        if (BuildConfig.DEBUG) {
            addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
        }
    }.build()


    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()
    }

    // 获取配置参数
    fun getConfigParams(): JSONObject {
        val packageName = GlobalConfig.PACKAGE_NAME
        val jsonObject = JSONObject()
        jsonObject.put("${packageName}_4", Build.MANUFACTURER) // 手机厂商
        jsonObject.put("${packageName}_5", Build.VERSION.SDK_INT) // android系统版本号
        jsonObject.put("${packageName}_8", BuildConfig.VERSION_NAME) // APP版本号，如：1.1.2
        jsonObject.put("${packageName}_9", AppPreferences.getInstance().getString("uuid", "")) // Android id
        jsonObject.put("${packageName}_10", AppPreferences.getInstance().getString("gid", "")) // Google advertiser id
        jsonObject.put("${packageName}_13", "android") // platform  默认android
        jsonObject.put("${packageName}_14", BuildConfig.VERSION_CODE)// android版本，如：13
        jsonObject.put("${packageName}_15", "google") // 渠道标识
        jsonObject.put("${packageName}_24", BuildConfig.BUILD_TYPE) // 环境
        val timeZone: TimeZone = TimeZone.getDefault()
        jsonObject.put("${packageName}_34", timeZone.id) // 手机本地时区，值如下格式：America/New_York
        return jsonObject
    }

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

        if (BuildConfig.DEBUG || !ifAgreePrivacy || ConfigBean.configBean.noEventKey.contains(key)) {
            return
        }

        val s = JSONObject()
            .put("action", key)
            .put("value", value)
            .put("ext", ext)


        val data = JSONObject()
            .put("data", s)
            .put("bp", getConfigParams())
            .toString()

        val body = AESHelper.encrypt(data)
            .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                LogEx.logDebug(TAG, "onFailure")
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.code == 200 && response.isSuccessful) {
                    LogEx.logDebug(TAG, "onResponse 200")
                }
            }
        })
    }


}