package com.gh.gamecenter.sensorsdata

import android.content.Context
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.tracker.Tracker
import com.gh.gamecenter.common.utils.EnvHelper
import com.gh.gamecenter.common.utils.PackageFlavorHelper
import com.lightgame.utils.Utils
import com.sensorsdata.analytics.android.sdk.SAConfigOptions
import com.sensorsdata.analytics.android.sdk.SensorsDataAPI
import com.sensorsdata.analytics.android.sdk.SensorsDataDynamicSuperProperties
import org.json.JSONException
import org.json.JSONObject

object SensorsHelper {
    private const val KEY_USER_ID = "identity_mongold_id"
    private const val KEY_OAID = "identity_oaid"

    private const val TAG = "SensorsHelper"

    private var isInit = false

    private var pendingTrackActionList = arrayListOf<() -> Unit>()

    @JvmStatic
    fun init(context: Context, channel: String) {
        // 初始化
        Utils.log(TAG, "init $channel")
        val serverUrl = if (EnvHelper.isDevEnv) BuildConfig.DEV_SA_SERVER_URL else BuildConfig.SA_SERVER_URL

        SensorsDataAPI.startWithConfigOptions(
            context,
            SAConfigOptions(serverUrl).apply {
                enableLog(PackageFlavorHelper.IS_TEST_FLAVOR)
                enableEncrypt(true)
                enableTransportEncrypt()
            })

        // 设置静态公共属性
        try {
            SensorsDataAPI.sharedInstance().registerSuperProperties(JSONObject().apply {
                put("channel", channel)
                put("dia", MetaUtil.getMeta().dia)
                put("launch_id", Tracker.launchId)
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }

        // 设置动态公共属性
        SensorsDataAPI.sharedInstance().registerDynamicSuperProperties(SensorsDataDynamicSuperProperties {
            try {
                return@SensorsDataDynamicSuperProperties JSONObject().apply {
                    put("session_id", Tracker.sessionId)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            null
        })

        isInit = true

        pendingTrackActionList.forEach {
            it.invoke()
        }

        pendingTrackActionList.clear()
    }

    // 设置用户属性
    @JvmStatic
    fun profileSet(key: String, value: String) {
        Utils.log(TAG, "profileSet k:$key v:$value")
        SensorsDataAPI.sharedInstance().profileSet(key, value)
    }

    // 设置用户属性（列表）
    @JvmStatic
    fun profileAppend(key: String, value: String) {
        Utils.log(TAG, "profileAppend k:$key v:$value")
        SensorsDataAPI.sharedInstance().profileAppend(key, value)
    }

    // 获取预置属性
    @JvmStatic
    fun getPresetProperties(key: String): Any? {
        try {
            return SensorsDataAPI.sharedInstance().presetProperties[key]
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    @JvmStatic
    fun login(loginId: String) {
        Utils.log(TAG, "login $loginId")
        SensorsDataAPI.sharedInstance().bind(KEY_USER_ID, loginId)
    }

    @JvmStatic
    fun logout(loginId: String) {
        Utils.log(TAG, "logout $loginId")
        SensorsDataAPI.sharedInstance().unbind(KEY_USER_ID, loginId)
    }

    @JvmStatic
    fun setOAID(oaid: String) {
        Utils.log(TAG, "setOAID $oaid")

        SensorsDataAPI.sharedInstance().bind("$$KEY_OAID", oaid)
    }

    @JvmStatic
    fun trackEvent(eventName: String, vararg kv: Any) {
        if (kv.isEmpty()) {
            trackEvent(eventName, json {  })
            Utils.log(TAG, "trackEvent $eventName")
            return
        }

        val json = json {  }

        for (i in kv.indices) {
            if (i % 2 != 0) {
                val key = (kv[i - 1] as? String) ?: "" // key必须为String
                val value = kv[i]
                if (key.isNotEmpty() && (value !is String || value.isNotEmpty())) {
                    json.put(key, value)
                }
            }
        }

        Utils.log(TAG, "trackEvent k:$eventName v:$json")

        trackEvent(eventName, json)
    }

    @JvmStatic
    fun trackEvent(eventName: String, jsonObject: JSONObject) {
        val action = {
            try {
                Utils.log("SensorsHelper", "eventName:$eventName\n ${jsonObject.toString(4)}")
                SensorsDataAPI.sharedInstance().track(eventName, jsonObject)
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }

        if (isInit) {
            action.invoke()
        } else {
            pendingTrackActionList.add(action)
        }
    }
}