package com.base.scanqrclear.fcm.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.base.scanqrclear.bean.NotificationSendBean
import com.base.scanqrclear.bean.NotificationSendBean.Companion.POPUP_WHERE_LOCK
import com.base.scanqrclear.bean.config.PopupConfigBean.Companion.popupConfigBean
import com.base.scanqrclear.fcm.notification.MyNotificationManager
import com.base.scanqrclear.helper.EventUtils
import com.base.scanqrclear.utils.AppPreferences
import com.base.scanqrclear.utils.KotlinExt.currentDate
import com.base.scanqrclear.utils.LogEx
import java.util.Objects

class ScreenStatusReceiver : BroadcastReceiver() {

    private val TAG = "ScreenStatusReceiver"

    override fun onReceive(context: Context, intent: Intent) {
        LogEx.logDebug(TAG, "onReceive")
        val action = intent.action
        when (Objects.requireNonNull<String?>(action)) {
            Intent.ACTION_SCREEN_ON -> isDeviceInteractive = true
            Intent.ACTION_SCREEN_OFF -> {
                isDeviceInteractive = false
                isSecureLockActive = true
            }

            Intent.ACTION_USER_PRESENT -> {
                isSecureLockActive = false
                if (isDeviceInteractive && !isSecureLockActive) {
                    if (popupConfigBean.screenS) {
                        LogEx.logDebug(TAG, "onReceive submitSendBean")
                        val sendBean = NotificationSendBean(
                            context,
                            POPUP_WHERE_LOCK,
                            canSend = { canScreenStatusReceiverPush() },
                            sendSuccess = { saveScreenPushedData() })
                        MyNotificationManager.submitSendBean(sendBean)
                    }
                }
            }
        }
    }


    companion object {

        private val TAG = "ScreenStatusReceiver"

        var isDeviceInteractive: Boolean = true
        var isSecureLockActive: Boolean = false

        fun registerScreenStatusReceiver(context: Context) {
            val intentFilter = IntentFilter()
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
            intentFilter.addAction(Intent.ACTION_SCREEN_ON)
            intentFilter.addAction(Intent.ACTION_USER_PRESENT)

            val applicationContext = context.applicationContext
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                applicationContext.registerReceiver(ScreenStatusReceiver(), intentFilter, Context.RECEIVER_EXPORTED)
            } else {
                applicationContext.registerReceiver(ScreenStatusReceiver(), intentFilter)
            }
        }


        /**
         * 当前天推送数量
         */
        private var todayScreenPush = 0
            get() {
                return AppPreferences.getInstance().getInt("todayScreenPush_${currentDate()}", field)
            }
            set(value) {
                field = value
                AppPreferences.getInstance().put("todayScreenPush_${currentDate()}", value, true)
            }

        /**
         * 上次成功推送
         */
        private var screenLastPushTime = 0L
            get() {
                return AppPreferences.getInstance().getLong("screenLastPushTime", field)
            }
            set(value) {
                field = value
                AppPreferences.getInstance().put("screenLastPushTime", value, true)
            }


        /**
         * 解锁是否可推送
         * 总的限制条件判断后才判断
         */
        fun canScreenStatusReceiverPush(): Boolean {
            if (!popupConfigBean.popupStatus) return false

            val popupScreenCount = popupConfigBean.popupScreenCount
            val flag1 = todayScreenPush <= popupScreenCount

            val minute = 60 * 1000L
            val interval = popupConfigBean.popupScreenInterval
            val passTime = System.currentTimeMillis() - screenLastPushTime
            val flag2 = screenLastPushTime == 0L || passTime > interval * minute

            val flag = flag1 && flag2

            if (!flag) {
                EventUtils.event(
                    "Notification_Error", "todayScreenPush=$todayScreenPush " +
                            "popupScreenCount=$popupScreenCount where=$POPUP_WHERE_LOCK"
                )
                LogEx.logDebug(
                    "canSendNotification",
                    "Notification_Error todayScreenPush=$todayScreenPush " +
                            "popupScreenCount=$popupScreenCount where=$POPUP_WHERE_LOCK"
                )
            }
            LogEx.logDebug(TAG, "canScreenStatusReceiverPush flag=$flag")
            return flag
        }

        /**
         * 推送成功后保存值
         */
        fun saveScreenPushedData() {
            todayScreenPush += 1
            screenLastPushTime = System.currentTimeMillis()
            LogEx.logDebug(TAG, "saveScreenPushedData")
        }

    }
}