package com.base.scanqrclear.fcm.notification

import android.os.Handler
import android.os.HandlerThread
import com.base.scanqrclear.BuildConfig
import com.base.scanqrclear.MyApplication
import com.base.scanqrclear.bean.NotificationSendBean
import com.base.scanqrclear.bean.config.PopupConfigBean.Companion.popupConfigBean
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.ToastUtils.toast

/**
 * 悬停通知
 */
object NotificationHoverUtils {

    private val TAG = "NotificationHoverUtils"
    private var handlerThread: HandlerThread? = null
    private var handler: Handler? = null

    /**
     * 发送悬停通知
     */
    fun sendHoverNotification(sendBean: NotificationSendBean) {

        val hoverStatus = popupConfigBean.popupHoverStatus
        val hoverCount = popupConfigBean.popupHoverCount
        val hoverDelay = popupConfigBean.popupHoverDelay.toLong()
        LogEx.logDebug(TAG, "hoverStatus=$hoverStatus hoverCount=$hoverCount hoverDelay=$hoverDelay")
        if (!hoverStatus) return

        stopNotificationHandler()

        if (handlerThread == null) {
            handlerThread = HandlerThread("NotificationHandlerThread")
            handlerThread?.start()
        }

        // 创建 Handler
        if (handler == null) {
            handlerThread?.let {
                handler = Handler(it.getLooper())
            }
        }

        for (i in 1..hoverCount) {
            val time = i * hoverDelay
            handler?.postDelayed({
//                LogEx.logDebug(TAG, "handler ${MyApplication.PAUSED_VALUE}")
                if (MyApplication.PAUSED_VALUE == 1) {
                    handler?.removeCallbacksAndMessages(null)
                } else {
                    LogEx.logDebug(TAG, "Hover time=$time")
                    NotificationUiUtil.setNotification(sendBean)
                    if (BuildConfig.DEBUG){
                        MyApplication.appContext.toast("Hover")
                    }
                }
            }, time)
        }
    }

    fun stopNotificationHandler() {
        // 停止 HandlerThread
        if (handler != null) {
            handler?.removeCallbacksAndMessages(null)
        }
        if (handlerThread != null) {
            handlerThread?.quit()
            handlerThread = null
        }
        handler = null
    }
}