package com.gh.gamecenter.common.tracker

import android.app.Activity
import android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner
import com.gh.gamecenter.core.runOnUiThread
import java.util.*

/**
 * launch_id 当前启动的唯一 id (每次应用冷启动或被内存回收时变更)
 * session_id 当前会话的唯一 id (应用切换至后台超30秒时变更)
 */
object Tracker : ITrack {

    private var mSessionId: String = ""
    private val mLaunchId by lazy { UUID.randomUUID().toString() }

    val sessionId: String
        get() = mSessionId

    val launchId: String
        get() = mLaunchId

    private var mIsInitialized = false

    @JvmStatic
    fun init(application: Application) {
        if (mIsInitialized) {
            return
        }

        runOnUiThread {
            ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleWatcher(this))
            application.registerActivityLifecycleCallbacks(ActivityLifecycleWatcher(this))
        }
        mIsInitialized = true
    }

    override fun onActivityStarted(activity: Activity) {
        val businessId = if (activity is IBusiness) activity.getBusinessId() else null

        TrackerLogger.logActivityStart(
            System.identityHashCode(activity).toString(),
            activity::class.java.simpleName,
            businessId
        )
    }

    override fun onActivityStopped(activity: Activity) {
        val businessId = if (activity is IBusiness) activity.getBusinessId() else null

        TrackerLogger.logActivityStop(
            System.identityHashCode(activity).toString(),
            activity::class.java.simpleName,
            businessId
        )
    }

    override fun onAppStarted() {
        TrackerLogger.logAppStart()
    }

    override fun onAppVisible(interval: Long) {
        TrackerLogger.logAppVisible(interval)
    }

    override fun onAppStopped() {
        TrackerLogger.logAppStop()
    }

    override fun onSessionChanged(sessionId: String) {
        mSessionId = sessionId
    }

}