package com.gamedog.statisticreporter.firbase


import android.content.Context
import android.os.Bundle
import com.ama.core.architecture.BaseApp
import com.google.firebase.Firebase
import com.google.firebase.FirebaseApp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.analytics
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.util.concurrent.ConcurrentHashMap


class FireBaseManager private constructor() {
    companion object {
        @Volatile
        private var INSTANCE: FireBaseManager? = null

        fun instance(): FireBaseManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: FireBaseManager().also { INSTANCE = it }
            }
        }
    }


    private val mAppContext = BaseApp.appContext()
    private val mBgScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    private val mMainScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)

    private lateinit var mFbAnalytics: FirebaseAnalytics
    private val mDefaultParams = ConcurrentHashMap<String, Any>()




    init {
        FirebaseApp.initializeApp(mAppContext)

        if (!::mFbAnalytics.isInitialized) {
            mFbAnalytics = Firebase.analytics// FirebaseAnalytics.getInstance(mAppContext)
        }
    }

    fun reportEvent(eventName: String, parameters: Map<String, Any>? = null) {
        if (!::mFbAnalytics.isInitialized) {
            throw IllegalStateException("FirebaseAnalyticsUtil not initialized. Call init() first.")
        }

        val bundle = Bundle().apply {
            // 默认参数添加
            mDefaultParams.forEach { (key, value) ->
                when (value) {
                    is String -> putString(key, value)
                    is Int -> putInt(key, value)
                    is Long -> putLong(key, value)
                    is Double -> putDouble(key, value)
                    is Float -> putFloat(key, value)
                    is Boolean -> putBoolean(key, value)
                }
            }

            // 本次事件特定参数添加
            parameters?.forEach { (key, value) ->
                when (value) {
                    is String -> putString(key, value)
                    is Int -> putInt(key, value)
                    is Long -> putLong(key, value)
                    is Double -> putDouble(key, value)
                    is Float -> putFloat(key, value)
                    is Boolean -> putBoolean(key, value)
                    else -> putString(key, value.toString())
                }
            }
        }

        mFbAnalytics.logEvent(eventName, bundle)
    }



    /**
     * 记录推荐事件（使用 Firebase 预设事件类型）
     * @param eventType 事件类型，如 FirebaseAnalytics.Event.SELECT_CONTENT
     * @param parameters 事件参数
     */
    fun reportRecommendedEvent(eventType: String, parameters: Bundle) {
        if (!::mFbAnalytics.isInitialized) {
            throw IllegalStateException("FirebaseAnalyticsUtil not initialized. Call init() first.")
        }
        mFbAnalytics.logEvent(eventType, parameters)
    }

    /**
     * 设置用户属性
     * @param propertyName 属性名称
     * @param propertyValue 属性值
     */
    fun setUserProperty(propertyName: String, propertyValue: String) {
        if (!::mFbAnalytics.isInitialized) return
        mFbAnalytics.setUserProperty(propertyName, propertyValue)
    }

    /**
     * 设置用户ID
     * @param userId 用户唯一标识
     */
    fun setUserId(userId: String) {
        if (!::mFbAnalytics.isInitialized) return
        mFbAnalytics.setUserId(userId)
    }

    /**
     * 设置当前屏幕
     * @param screenName 屏幕名称
     * @param screenClass 屏幕类名（可选）
     */
    fun setCurrentScreen(context: Context, screenName: String, screenClass: String? = null) {
        if (!::mFbAnalytics.isInitialized) return

        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.SCREEN_NAME, screenName)
            screenClass?.let { putString(FirebaseAnalytics.Param.SCREEN_CLASS, it) }
        }

        mFbAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, bundle)
    }

    /**
     * 设置默认事件参数（将自动添加到每个事件中）
     * @param parameters 默认参数映射
     */
    fun setDefaultEventParameters(parameters: Map<String, Any>) {
        mDefaultParams.clear()
        mDefaultParams.putAll(parameters)
    }

    /**
     * 添加单个默认事件参数
     */
    fun addDefaultEventParameter(key: String, value: Any) {
        mDefaultParams[key] = value
    }

    /**
     * 清除所有默认事件参数
     */
    fun clearDefaultEventParameters() {
        mDefaultParams.clear()
    }

}


