package com.base.locationsharewhite.fcm

import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import com.base.locationsharewhite.fcm.PopupConstObject.popup_hover_count
import com.base.locationsharewhite.fcm.PopupConstObject.popup_hover_delay
import com.base.locationsharewhite.fcm.PopupConstObject.popup_hover_status
import com.base.locationsharewhite.helper.MyApplication
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.LogEx

object NotificationHoverUtils {

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

    /**
     * 发送悬停通知
     */
    fun sendHoverNotification(context: Context) {

        val hoverCount = AppPreferences.getInstance().getString(popup_hover_count, "0").toInt()
        val hoverDelay = AppPreferences.getInstance().getString(popup_hover_delay, "0").toLong()
        val hoverStatus = AppPreferences.getInstance().getString(popup_hover_status, "0").toInt()
        if (hoverStatus == 0) return

        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(Runnable {
                LogEx.logDebug(TAG, "handler ${MyApplication.PAUSED_VALUE}")
                if (MyApplication.PAUSED_VALUE == 1) {
                    handler?.removeCallbacksAndMessages(null)
                } else {
                    LogEx.logDebug(TAG, "handler send notification")
                    NotificationUiUtil.setActionNotification(context, NotificationUiUtil.hoverActionId)
                }
            }, time)
        }
    }

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