package com.gh.gamecenter.common.tracker

import android.content.Context
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.common.exposure.meta.MetaUtil.getBase64EncodedAndroidId
import com.gh.gamecenter.common.exposure.meta.MetaUtil.getBase64EncodedIMEI
import com.gh.gamecenter.common.loghub.LoghubUtils
import com.gh.gamecenter.common.utils.DarkModeUtils
import com.gh.gamecenter.common.utils.tryCatchInRelease
import com.gh.gamecenter.core.provider.IAppProvider
import com.lightgame.utils.Utils
import org.json.JSONException
import org.json.JSONObject

object TrackerLogger {

    private const val LOG_STORE = "launch_activity"

    fun logAppStart() {
        logAppVisible(0)
    }

    fun logAppVisible(interval: Long) {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)
            payloadObject.put("interval", interval)

            jsonObject.put("event", "app_visible")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, true)
    }

    fun logAppStop() {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)

            jsonObject.put("event", "app_invisible")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, true)
    }

    fun logActivityStart(
        activityId: String,
        activityName: String,
        activityBusinessId: Pair<String, String>? = null
    ) {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)
            payloadObject.put("activity_id", activityId)
            payloadObject.put("activity_name", activityName)
            if (activityBusinessId != null) {
                payloadObject.put("activity_primary_business_id", activityBusinessId.first)
                if (activityBusinessId.second.isNotEmpty()) {
                    payloadObject.put("activity_secondary_business_id", activityBusinessId.second)
                }
            }

            jsonObject.put("event", "activity_visible")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, false)
    }

    fun logActivityStop(
        activityId: String,
        activityName: String,
        activityBusinessId: Pair<String, String>? = null
    ) {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)
            payloadObject.put("activity_id", activityId)
            payloadObject.put("activity_name", activityName)
            if (activityBusinessId != null) {
                payloadObject.put("activity_primary_business_id", activityBusinessId.first)
                if (activityBusinessId.second.isNotEmpty()) {
                    payloadObject.put("activity_secondary_business_id", activityBusinessId.second)
                }
            }

            jsonObject.put("event", "activity_invisible")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, false)
    }

    @JvmStatic
    fun logHomeTabSelected(
        tabPosition: Int,
        tabContent: String
    ) {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)
            payloadObject.put("tab_position", tabPosition)
            payloadObject.put("tab_content", tabContent)

            jsonObject.put("event", "home_tab_select")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, false)
    }

    @JvmStatic
    fun logAppLaunch(context: Context) {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        val appProvider = TheRouter.get(IAppProvider::class.java)

        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)
            payloadObject.put("package_name", context.packageName)
            payloadObject.put("app_name", appProvider?.getAppName())
            payloadObject.put("is_night_mode", DarkModeUtils.isDarkModeOn(context))
            payloadObject.put("is_night_mode_auto_switch", DarkModeUtils.isFollowSystemDarkModeFromSp())

            jsonObject.put("event", "app_launch")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, true)
    }

    @JvmStatic
    fun logAppLaunchSuccessful() {
        val jsonObject = JSONObject()
        val payloadObject = JSONObject()
        tryCatchInRelease {
            payloadObject.put("launch_id", Tracker.launchId)
            payloadObject.put("session_id", Tracker.sessionId)

            jsonObject.put("event", "app_launch_successful")
            jsonObject.put("payload", payloadObject)
            jsonObject.put("meta", getMeta())
        }
        uploadToLoghub(jsonObject, true)
    }

    private fun uploadToLoghub(jsonObject: JSONObject, uploadImmediately: Boolean) {
        jsonObject.put("timestamp", System.currentTimeMillis() / 1000)

        Utils.log("Tracker -> $jsonObject")
        LoghubUtils.log(jsonObject, LOG_STORE, uploadImmediately)
    }

    private fun getMeta(): JSONObject {
        val meta = MetaUtil.getMeta()

        val metaObject = JSONObject()
        try {
            metaObject.put("dia", getBase64EncodedAndroidId())
            metaObject.put("android_version", meta.android_version)
            metaObject.put("app_version", meta.appVersion)
            metaObject.put("channel", meta.channel)
            metaObject.put("gid", meta.gid)
            metaObject.put("oaid", meta.oaid)
            metaObject.put("rom", meta.rom)
            metaObject.put("jnfj", getBase64EncodedIMEI())
            metaObject.put("manufacturer", meta.manufacturer)
            metaObject.put("model", meta.model)
            metaObject.put("network", meta.network)
            metaObject.put("user_id", meta.userId)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return metaObject
    }

}