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_PACKAGE
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

class PackageStatusReceiver() : BroadcastReceiver() {

    companion object {

        private val TAG = "PackageStatusReceiver"

        fun registerPackageStatusReceiver(context: Context) {
            LogEx.logDebug(TAG, "registerPackageStatusReceiver")
            val intentFilter = IntentFilter().apply {
                addAction(Intent.ACTION_PACKAGE_ADDED)
                addAction(Intent.ACTION_PACKAGE_REMOVED)
                addDataScheme("package")
            }
            val applicationContext = context.applicationContext
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                applicationContext.registerReceiver(
                    PackageStatusReceiver(),
                    intentFilter,
                    Context.RECEIVER_EXPORTED
                )
            } else {
                applicationContext.registerReceiver(PackageStatusReceiver(), intentFilter)
            }
        }

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

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

        /**
         * 安装卸载是否可推送
         * 总的限制条件判断后才判断
         */
        fun canPackageStatusReceiverPush(): Boolean {

            if (!popupConfigBean.packageS) return false

            val popupPackageCount = popupConfigBean.popupPackageCount
            val flag1 = todayPackagePush <= popupPackageCount

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


            val flag = flag1 && flag2
            if (!flag) {
                EventUtils.event(
                    "Notification_Error", "todayPackagePush=$todayPackagePush " +
                            "popupPackageCount=$popupPackageCount where=$POPUP_WHERE_PACKAGE"
                )
                LogEx.logDebug(
                    "canSendNotification", "Notification_Error todayPackagePush=$todayPackagePush " +
                            "popupPackageCount=$popupPackageCount where=$POPUP_WHERE_PACKAGE"
                )
            }
            return flag
        }

        /**
         * 推送成功后保存值
         */
        fun savePackagePushedData() {
            todayPackagePush += 1
            packageLastPushTime = System.currentTimeMillis()
        }


    }

    override fun onReceive(context: Context, intent: Intent?) {
        val action = intent?.action
        LogEx.logDebug(TAG, "onReceive action=$action")

        if (action == Intent.ACTION_PACKAGE_ADDED || action == Intent.ACTION_PACKAGE_REMOVED) {

            val sendBean = NotificationSendBean(context, POPUP_WHERE_PACKAGE, canSend = {
                canPackageStatusReceiverPush()
            }, sendSuccess = {
                savePackagePushedData()
            })
            MyNotificationManager.submitSendBean(sendBean)
        }
    }
}