package com.rgt.superr.business.push.notification

import com.rgt.superr.MyApplication
import com.rgt.superr.bean.push.NotificationSendBean
import com.rgt.superr.bean.config.PopupConfigBean.Companion.popupConfigBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 通知悬停
 */
object NotificationHoverUtils {
    private val TAG = "NotificationHoverUtils"
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    private var notificationJobs = mutableListOf<Job>()

    /**
     * 发送悬停通知
     */
    fun sendHoverNotification(sendBean: NotificationSendBean) {
        val hoverStatus = popupConfigBean.popupHoverStatus
        val hoverCount = popupConfigBean.popupHoverCount
        val hoverDelay = popupConfigBean.popupHoverDelay.toLong()

        if (!hoverStatus) return

        // 取消之前的任务
        stopNotificationHandler()

        for (i in 1..hoverCount) {
            val time = i * hoverDelay
            val job = scope.launch {
                delay(time)
                if (MyApplication.PAUSED_VALUE != 1) {
                    async(Dispatchers.Main) {
                        NotificationUiUtil.sendCustomNotification(sendBean)
                    }.await()
                }
            }
            notificationJobs.add(job)
        }
    }

    private fun stopNotificationHandler() {
        // 取消所有协程任务
        notificationJobs.forEach { it.cancel() }
        notificationJobs.clear()
    }

    /**
     * 清理资源
     */
    fun destroy() {
        stopNotificationHandler()
        scope.cancel()
    }
}