package com.base.locationsharewhite.fcm

import android.app.NotificationManager
import android.content.Context
import android.util.SparseArray
import androidx.core.util.isEmpty
import androidx.core.util.size
import com.base.locationsharewhite.notification.NotificationBean
import com.base.locationsharewhite.notification.NotificationHoverUtils
import com.base.locationsharewhite.notification.NotificationMgr
import com.base.locationsharewhite.service.StayNotificationService.Companion.startStayNotification
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.KotlinExt.toFormatMinute
import com.base.locationsharewhite.utils.KotlinExt.toFormatTime4

/**
 * 推送消息通知栏相关管理类
 */
object MsgMgr {

    const val SAVE_DATE = "SAVE_DATE"

    /**
     * 保存的时间，用来判断是否是当天，不是当天要重置计数次数,这里的和admob的广告当天记录时间用的一样的哦
     */
    var saveDate
        get() = AppPreferences.getInstance()
            .getString(SAVE_DATE, System.currentTimeMillis().toFormatTime4())
        set(value) = AppPreferences.getInstance().put(SAVE_DATE, value)

    /**
     *  FCM主题订阅 Topic 包名+首次启动的当前的分钟
     */
    private var topic
        get() = AppPreferences.getInstance().getString("topic", "")
        set(value) = AppPreferences.getInstance().put("topic", value)


    var hoverActionId = -1
        private set

    private var actionKeyIndex = 0

    private lateinit var hoverConfig: MsgConfigBean

    var remoteViewContainer: SparseArray<NotificationBean>? = null

    fun init(context: Context, packageName: String, msgConfig: MsgConfig) {
        hoverConfig = msgConfig.hover
        remoteViewContainer = msgConfig.remoteViewContainer
        //初始化SDK
        FCMManager.initFirebase(context)
        //注册fcm主题订阅
        var topic = topic
        if (topic.isEmpty()) {
            val topicNumber = System.currentTimeMillis().toFormatMinute()
            topic = packageName + "_$topicNumber"
            MsgMgr.topic = topic
        }
        FCMManager.subscribeToTopic(topic)


        //判断是否配置自定义通知栏事件
        if (remoteViewContainer?.isEmpty() != false) return
        //注册几个状态广播监听
        ScreenStatusReceiver.registerScreenReceiver(context, msgConfig.unlock)
        PackageStatusReceiver.registerBatteryReceiver(context, msgConfig.packageChange)
        BatteryStatusReceiver.registerBatteryReceiver(context, msgConfig.battery)

        //根据配置设置定时推送
        if (!TimerManager.isTaskTimerActive) {
            TimerManager
                .scheduleTask(
                    (msgConfig.timer.value1 * 60 * 1000).toLong(),
                    (msgConfig.timer.value2 * 60 * 1000).toLong()
                )
        }
    }

    /**
     * 发送通知
     *
     * @param context
     * @param actionId  通知栏的事件id，这个是自己定的，每个应用可能不一样
     * @param hoverOpen  悬停通知是否关闭，0=关闭，1=开启
     */
    fun sendNotification(
        context: Context,
        actionId: Int = getNextActionId(),
        hoverOpen: Int = if (this::hoverConfig.isInitialized) hoverConfig.value1 else 0
    ) {
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (!notificationManager.areNotificationsEnabled()) return
        //先判断是否有自定义通知栏装入
        if (remoteViewContainer?.isEmpty() != false) return
        val bean = remoteViewContainer?.get(actionId) ?: return
        NotificationMgr.sendNotification(
            context,
            bean.intent,
            bean.bigRemoteViews,
            bean.smallRemoteViews
        )
        if (hoverOpen == 1) {
            if (hoverActionId != -1) {
                //如果当前悬浮有事件，就重置整个悬浮逻辑
                stopHoverNotification()
            }
            //记录当前悬停的通知事件id
            hoverActionId = actionId
            //悬停通知开启了
            //计算次数，因为系统默认是5s，这里计算多久再次发送通知
            val count = hoverConfig.value2 / 5
            //如果悬浮通知配置小于了系统的默认值那就没必要在发送延迟了
            if (count <= 1) return
            //发送延迟通知
            NotificationHoverUtils.sendHoverNotification(context, count - 1, 5 - 1)
        }
    }

    /**
     * 开启常驻通知栏
     */
    fun startPermanentNotification(context: Context) {
        context.startStayNotification()
    }

    /**
     * 停止悬停通知的延迟队列
     */
    fun stopHoverNotification() {
        hoverActionId = -1
        NotificationHoverUtils.stopNotificationHandler()
    }

    /**
     *循环输出通知栏不同的事件
     * @return 当前循环输出的actionId
     */
    private fun getNextActionId(): Int {
        val size = remoteViewContainer?.size ?: 0
        val actionId = remoteViewContainer?.keyAt(actionKeyIndex) ?: 0
        if (size > actionKeyIndex + 1) {
            actionKeyIndex++
        } else actionKeyIndex = 0
        return actionId
    }
}