package com.base.easyfilemanager.helps

import android.util.Log
import com.base.easyfilemanager.BuildConfig
import com.base.easyfilemanager.helps.ConfigHelper.ifAgreePrivacy
import com.base.easyfilemanager.utils.SPUtils
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 = ConfigHelper.packageName
        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
        }

        val filterKey = arrayOf(
            "click_start_to_use",
            "install_referrer",
            "ad_pull_start",
            "ad_prepare_show",
            "notification_jump",
            "ad_pull",
            "ad_show",
            "ad_click",
            "bigimage_ad_click",
            "bigimage_ad_show",
            "ad_price",
            "fcm_receiver",
            "fcm_message_received"
        )
        if (!filterKey.contains(key)) {
            return
        }

        if (isSingleEvent) {
            val stringSet = SPUtils.getInstance().getStringSet("singleEvent")
            if (stringSet.contains(key)) {
                return
            }
        }
        val pkg = ConfigHelper.packageName
        val s = JSONObject()
            .put("action", key)
            .put("value", value)
            .put("ext", ext)
        val s2 = JSONObject()
            .put("${pkg}_3", SPUtils.getInstance().getString("Equipment"))
            .put("${pkg}_4", SPUtils.getInstance().getString("Manufacturer"))
            .put("${pkg}_5", SPUtils.getInstance().getString("svn"))
            .put("${pkg}_9", SPUtils.getInstance().getString("uuid"))
            .put("${pkg}_10", SPUtils.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)
        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)
                }
            }
        })
    }
}