package com.zxdemo.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.util.Log
import com.swiftcleaner.chovey.model.bean.Global.NOTIFICATION_WHERE_UNLOCK
import com.swiftcleaner.chovey.model.bean.Global.lockNotificationStatus
import com.zxdemo.ZxApplication
import com.zxdemo.notity.NotificationUtils
import com.zxdemo.utils.SpUtils

class UnlockReceiver : BroadcastReceiver() {

    companion object {
        var mIsScreenOn = true
        var isLock = false
    }

    fun initBroadcast(context: Context) {
        Log.d("onReceive", "initBroadcast")
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_SCREEN_OFF)
        filter.addAction(Intent.ACTION_SCREEN_ON)
        filter.addAction(Intent.ACTION_USER_PRESENT)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            context.registerReceiver(this, filter, Context.RECEIVER_EXPORTED)
        } else {
            context.registerReceiver(this, filter)
        }
    }


    override fun onReceive(context: Context, intent: Intent) {
        Log.e("UnlockReceiver", "onReceive")
        val action = intent.action

        when (action) {
            Intent.ACTION_SCREEN_ON -> {
                mIsScreenOn = true
            }

            Intent.ACTION_SCREEN_OFF -> {
                mIsScreenOn = false
                isLock = true
            }

            Intent.ACTION_USER_PRESENT -> {
                isLock = false
                // 执行解锁后的操作，比如启动服务、发送通知等
                val lockNotificationStatus =
                    SpUtils.getInstance().getInt(lockNotificationStatus, 0)

                //获取当前时间和上一次推送的时间
                if (lockNotificationStatus == 1 && mIsScreenOn && !isLock) {
                    NotificationUtils.sendNotification(ZxApplication.context, NOTIFICATION_WHERE_UNLOCK)
                }
            }

            else -> {

            }
        }
    }
}