package com.base.browserwhite.fcm

import android.content.Context
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import com.base.browserwhite.MyApplication
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.ID_APP_PROCESS
import com.base.browserwhite.bean.ConstObject.ID_CLEAN_JUNK_MEMORY
import com.base.browserwhite.bean.ConstObject.ID_JUNK_CLEANER
import com.base.browserwhite.bean.ConstObject.ID_NEWS
import com.base.browserwhite.bean.ConstObject.ID_WEATHER
import com.base.browserwhite.help.EventUtils
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.TimeUtils.formatTimeH
import com.base.browserwhite.utils.TimeUtils.isTimeBetweenEightAndTenPM
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

object NotificationPushUtil {

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

    const val PUSH_WHERE_TIMBER = "push_where_timber"//定时推送
    const val PUSH_WHERE_UN_INSTALL_BROADCAST = "push_where_un_install_broadcast"//安装卸载广播
    const val PUSH_WHERE_UNLOCK = "push_where_unlock"//解锁推送
    const val PUSH_WHERE_FCM = "push_where_fcm"//fcm推送

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

    /**
     * 统一调用入口
     * @param where [PUSH_WHERE_TIMBER]
     */
    fun Context.sendNotificationWhere(setActionId: Int?, where: String) {
        val actionId: Int = setActionId ?: getNextNotificationId()

        if (MyApplication.PAUSED_VALUE == 1) {
            return
        }

        NotificationUiUtil.sendNotification(this, actionId, where)

        EventUtils.event("showNotification", where, null, false)
//        AppPreferences.getInstance().putInt("notificationCount_${getCurrentDate()}", todayShowCount + 1)

        beginPushTimber(this)
        beginNewsPushTimber(this)
    }

    /**
     * 是否可以推送判断
     */
    fun canPushNotification(actionId: Int, where: String): Boolean {
        //默认可以推送
        var canPush: Boolean = true

        //        val maxShowNotificationCount = AppPreferences.getInstance().getString("maxShowNotificationCount", "200").toInt()
//        val todayShowCount = AppPreferences.getInstance().getInt("notificationCount_${getCurrentDate()}", 0)
//        if (todayShowCount >= maxShowNotificationCount) {
//            return
//        }

//        val interval: Int = AppPreferences.getInstance().getString("notificationInterval", "60").toIntOrNull() ?: 60
//        val lastTime: Long = AppPreferences.getInstance().getLong("last_notification_time", 0)
//        val nowTime = System.currentTimeMillis()
//        val x = nowTime - lastTime
//        if (x < (interval * 1000)) {
//            return
//        }

        when (actionId) {
            ID_JUNK_CLEANER -> {
                canPush = canPushJunkClean(where)
            }

            ID_CLEAN_JUNK_MEMORY -> {

            }

            ID_NEWS -> {
                canPush = canPushNews(where)
                LogEx.logDebug(TAG, "ID_NEWS canPush=$canPush")
            }

            ID_WEATHER -> {
                canPush = canPushWeather(where)
                LogEx.logDebug(TAG, "ID_WEATHER canPush=$canPush")
            }

            ID_APP_PROCESS -> {
                canPush = canPushAppProcess(where)
                LogEx.logDebug(TAG, "ID_APP_PROCESS canPush=$canPush")
            }

        }
        return canPush
    }


    private fun beginPushTimber(context: Context) {

        val open: Int = AppPreferences.getInstance().getString("open", "0").toIntOrNull() ?: 0

        if (open == 1) {
            val num: Int = AppPreferences.getInstance().getString("num", "0").toIntOrNull() ?: 0
            val delay: Long = AppPreferences.getInstance().getString("delay", "0").toLongOrNull() ?: 0L
            handlerThread = HandlerThread("NotificationHandlerThread")
            handlerThread?.start()

            // 创建 Handler
            handler = Handler(handlerThread!!.looper)
            for (i in 1..num) {
                val time = i * delay
                handler?.postDelayed(Runnable {

                    if (MyApplication.PAUSED_VALUE != 1
                        && ScreenStatusReceiver.isDeviceInteractive()
                        && !ScreenStatusReceiver.isSecureLockActive()
                    ) {
                        context.sendNotificationWhere(null, PUSH_WHERE_TIMBER)
                    }
                    if (MyApplication.PAUSED_VALUE == 1) {
                        if (handler != null) {
                            handler?.removeCallbacksAndMessages(null)
                        }
                        return@Runnable
                    }
                }, time)
            }
        }
    }

    private var newsHandlerThread: HandlerThread? = null
    private var newsHandler: Handler? = null
    private var newsRunnable: Runnable? = null
    private fun beginNewsPushTimber(context: Context) {

        if (newsHandler != null || newsHandlerThread != null || newsRunnable != null) return
        newsHandlerThread = HandlerThread("NotificationHandlerThreadNews")
        newsHandlerThread?.start()

        newsHandler = Handler(newsHandlerThread!!.looper)

        newsRunnable = Runnable {

            LogEx.logDebug(TAG, "beginNewsPushTimber")
            context.sendNotificationWhere(ID_NEWS, PUSH_WHERE_TIMBER)
            newsRunnable?.let { newsHandler?.postDelayed(it, 30 * 60 * 1000) }

        }

//        newsRunnable?.let { newsHandler?.postDelayed(it, 5 * 60 * 1000) }
        newsRunnable?.let { newsHandler?.post(it) }
    }

    fun stopNotificationHandlerNews() {
        // 停止 HandlerThread
        if (newsHandler != null) {
            newsHandler?.removeCallbacksAndMessages(null)
        }
        if (newsHandlerThread != null) {
            newsHandlerThread?.quit()
            newsHandlerThread = null
        }
        newsHandler = null
    }


    //天气
    private fun canPushWeather(where: String): Boolean {
        val lastPushTime = AppPreferences.getInstance().getLong("last_notification_time", 0)

        if (where == PUSH_WHERE_TIMBER || where == PUSH_WHERE_UNLOCK) {
            return lastPushTime == 0L || System.currentTimeMillis() - lastPushTime > 3 * 60 * 60 * 1000
        } else {
            return false
        }
    }

    //清理
    private fun canPushJunkClean(where: String): Boolean {
        if (where == PUSH_WHERE_TIMBER || where == PUSH_WHERE_UNLOCK) {
            //last push
            val lastPushTime = AppPreferences.getInstance().getLong("last_junk_notification_time", 0)
            val flag1 = lastPushTime == 0L || System.currentTimeMillis() - lastPushTime > 24 * 60 * 60 * 1000

            //last use
            val lastUseJunkTime = AppPreferences.getInstance().getLong("last_use_junk_clean", 0)
            val flag2 = lastUseJunkTime == 0L || System.currentTimeMillis() - lastUseJunkTime > 24 * 60 * 60 * 1000

            return flag1 || flag2
        } else {
            return false
        }
    }

    //新闻
    private fun canPushNews(where: String): Boolean {
        return true
        if (where == PUSH_WHERE_TIMBER || where == PUSH_WHERE_UNLOCK) {
            val time = System.currentTimeMillis().formatTimeH()
            val lashPushTime = AppPreferences.getInstance().getLong("last_news_notification_time", 0).formatTimeH()
            return isTimeBetweenEightAndTenPM() && time != lashPushTime
        } else {
            return false
        }
    }

    //app进程
    private fun canPushAppProcess(where: String): Boolean {
        if (where == PUSH_WHERE_TIMBER || where == PUSH_WHERE_UNLOCK) {
            val lastPushTime = AppPreferences.getInstance().getLong("last_process_notification_time", 0)
            val flag1 = lastPushTime == 0L || System.currentTimeMillis() - lastPushTime > 24 * 60 * 60 * 1000

            val lastUseTime = AppPreferences.getInstance().getLong("last_process_use_time", 0)
            val flag2 = lastUseTime == 0L || System.currentTimeMillis() - lastUseTime > 24 * 60 * 60 * 1000
            return flag1 || flag2
        } else {
            return false
        }
    }


    private var currentNotificationIdIndex = -1

    private fun getNextNotificationId(): Int {
        // 将当前通知 ID 索引加 1
        currentNotificationIdIndex++

        // 如果当前通知 ID 索引超出列表范围，则将其重置为 0
        if (currentNotificationIdIndex >= NOTIFICATION_IDS.size) {
            currentNotificationIdIndex = 0
        }

        // 返回下一个通知 ID
        return NOTIFICATION_IDS[currentNotificationIdIndex]
    }

    private val NOTIFICATION_IDS = intArrayOf(
        ConstObject.ID_JUNK_CLEANER,
        ConstObject.ID_CLEAN_JUNK_MEMORY,
        ConstObject.ID_NEWS,
        ConstObject.ID_APP_PROCESS,
        ConstObject.ID_WEATHER
    )

    private fun getCurrentDate(): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val currentDate = Calendar.getInstance().time
        return dateFormat.format(currentDate)
    }

}