package com.gh.gamecenter.sensorsdata

import android.content.Context
import android.text.TextUtils
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.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_GID = "identity_g_id"

    private const val TAG = "SensorsHelper"

    // 目前正在使用的 gid
    private var mCurrentGid = ""

    @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(EnvHelper.isDevEnv)
                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
        })
    }

    // 设置用户属性
    @JvmStatic
    fun profileSet(key: String, value: String) {
        Utils.log(TAG, "profileSet k:$key v:$value")
        SensorsDataAPI.sharedInstance().profileSet(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 setGid(gid: String) {
        Utils.log(TAG, "setGid $gid")

        // 当前绑定的 gid 与即将绑定的 gid 不一样时，先解绑旧的 gid
        if (mCurrentGid.isNotEmpty() && mCurrentGid != gid) {
            SensorsDataAPI.sharedInstance().unbind(KEY_GID, mCurrentGid)
        }

        mCurrentGid = gid
        SensorsDataAPI.sharedInstance().bind(KEY_GID, gid)
    }

    @JvmStatic
    fun trackEvent(eventName: String, vararg kv: String) {
        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]
                val value = kv[i]
                if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                    json.put(key, value)
                }
            }
        }

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

        trackEvent(eventName, json)
    }

    @JvmStatic
    fun trackEvent(eventName: String, jsonObject: JSONObject) {
        try {
            SensorsDataAPI.sharedInstance().track(eventName, jsonObject)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }
}