package com.base.locationsharewhite.fcm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.base.locationsharewhite.fcm.NotificationUiUtil.sendNotificationIfCan
import com.base.locationsharewhite.fcm.PopupConstObject.POPUP_WHERE_LOCK
import com.base.locationsharewhite.fcm.PopupConstObject.lockS
import com.base.locationsharewhite.fcm.PopupConstObject.popup_screen_count
import com.base.locationsharewhite.fcm.PopupConstObject.popup_screen_interval
import com.base.locationsharewhite.helper.EventUtils
import com.base.locationsharewhite.utils.AppPreferences
import com.base.locationsharewhite.utils.KotlinExt.currentDate
import com.base.locationsharewhite.utils.LogEx
import java.util.Objects

class ScreenStatusReceiver : BroadcastReceiver() {


    override fun onReceive(context: Context, intent: Intent) {
        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) {
                    val secureSetting = AppPreferences.getInstance().getString(lockS, "1").toInt()
                    if (secureSetting == 1) {
                        sendNotificationIfCan(context, POPUP_WHERE_LOCK, null)
                    }
                }
            }
        }
    }


    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 {
            val popupScreenCount = AppPreferences.getInstance().getString(popup_screen_count, "20").toInt()
            val flag1 = todayScreenPush <= popupScreenCount

            val minute = 60 * 1000L
            val default = 1 * minute

            val interval = AppPreferences.getInstance().getString(popup_screen_interval, default.toString()).toLong()
            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"
                )
            }
            return flag
        }

        /**
         * 推送成功后保存值
         */
        fun saveScreenPushedData(where: String, actionId: String) {
            if (where == POPUP_WHERE_LOCK) {
                todayScreenPush += 1
                screenLastPushTime = System.currentTimeMillis()
            }
        }

    }
}