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.utils.AppPreferences
import com.base.locationsharewhite.utils.KotlinExt.toFormatTime4

class ScreenStatusReceiver(private val configBean: MsgConfigBean) : BroadcastReceiver() {

    private var count
        get() = AppPreferences.getInstance().getInt("screen_count", 0)
        set(value) = AppPreferences.getInstance().putInt("screen_count", value)

    private var date
        get() = AppPreferences.getInstance().getLong("screen_date", 0)
        set(value) = AppPreferences.getInstance().putLong("screen_date", value)

    companion object {
        var isDeviceInteractive = true
            private set
        var isSecureLockActive = false
            private set

        fun registerScreenReceiver(context: Context, configBean: MsgConfigBean) {
            val intentFilter = IntentFilter().apply {
                addAction(Intent.ACTION_SCREEN_OFF)
                addAction(Intent.ACTION_SCREEN_ON)
                addAction(Intent.ACTION_USER_PRESENT)
            }
            val applicationContext = context.applicationContext
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                applicationContext.registerReceiver(
                    ScreenStatusReceiver(configBean),
                    intentFilter,
                    Context.RECEIVER_EXPORTED
                )
            } else {
                applicationContext.registerReceiver(ScreenStatusReceiver(configBean), intentFilter)
            }
        }
    }

    override fun onReceive(context: Context, intent: Intent?) {
        val action = intent?.action
        when (action) {
            Intent.ACTION_SCREEN_ON -> {
                isDeviceInteractive = true
            }

            Intent.ACTION_SCREEN_OFF -> {
                isDeviceInteractive = false
                isSecureLockActive = true
            }

            Intent.ACTION_USER_PRESENT -> {
                isSecureLockActive = false
                if (isDeviceInteractive) {
                    val currentMillis = System.currentTimeMillis()
                    val currentDate = currentMillis.toFormatTime4()
                    if (currentDate != MsgMgr.saveDate) {
                        //不是当天就重置
                        MsgMgr.saveDate = currentDate
                        count = 0
                    }
                    if ((configBean.value2 < 0 || count < configBean.value2) && ((currentMillis - date) / 1000 / 60).toInt() > configBean.value1) {
                        //推送次数没有达到限制并且展示的最小时间间隔大于配置时间(分钟)
                        count += 1
                        date = System.currentTimeMillis()
                        MsgMgr.sendNotification(context)
                    }
                }
            }
        }

    }
}