package com.base.datarecovery.utils

import android.os.Build
import android.util.Log
import com.base.datarecovery.BuildConfig
import com.base.datarecovery.GlobalConfig
import com.base.datarecovery.bean.ConstObject.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
import java.util.Locale
import java.util.TimeZone

object EventUtils {
    private val push_limit by lazy {
        listOf(
            "showNotification",
            "Notification_Popup",
            "alarm_push",
            "FCM_Received",
            "workmanager_live",
            "workmanager",
            "Notification_Error",
            "alarm_push2"
        )
    }
    val isPushReportSwitch
        get() = AppPreferences.getInstance().getString("push_report_switch", "0").toInt()
    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 event(
        key: String,
        value: String? = null,
        ext: JSONObject? = null,
        isSingleEvent: Boolean = false
    ) {
        if (!ifAgreePrivacy) {
            return
        }
        if (isPushReportSwitch==0 && push_limit.any { key.startsWith(it, ignoreCase = true) }) {
            return
        }


        val pkg =  GlobalConfig.PACKAGE_NAME
        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", getDeviceName())
            .put("${pkg}_4", Build.MANUFACTURER)
            .put("${pkg}_5", Build.VERSION.SDK_INT)
            .put("${pkg}_8", BuildConfig.VERSION_NAME)
            .put("${pkg}_9", AppPreferences.getInstance().getString("uuid", ""))
            .put("${pkg}_10", AppPreferences.getInstance().getString("gid", ""))
            .put("${pkg}_13", "android")
            .put("${pkg}_14", BuildConfig.VERSION_CODE)
            .put("${pkg}_15", "google")
            .put("${pkg}_24", BuildConfig.BUILD_TYPE)
            .put("${pkg}_34", timeZoneId)
        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) {
                if(key == "fcm_message_received"){
                    Log.e("MXL", "token上报成功 " )
                    AppPreferences.getInstance().put("token_success", AppPreferences.getInstance().getInt("token_success",0)+1)
                }
            }
        })
    }
    fun getDeviceName(): String? {
        val manufacturer = Build.MANUFACTURER
        val model = Build.MODEL
        val flag = model.lowercase(Locale.getDefault()).startsWith(manufacturer.lowercase(Locale.getDefault()))

        return if (flag) {
            if (model.isNullOrEmpty()) {
                model
            } else {
                model.substring(0, 1)
                    .uppercase(Locale.getDefault()) + model.substring(1)
                    .lowercase(Locale.getDefault())
            }

        } else {
            val ss = if (manufacturer.isNullOrEmpty()) {
                manufacturer
            } else {
                manufacturer.substring(0, 1)
                    .uppercase(Locale.getDefault()) + manufacturer.substring(1)
                    .lowercase(Locale.getDefault())
            }
            "$ss $model"
        }
    }
}