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.PopupConstObject.POPUP_WHERE_PACKAGE
import com.base.locationsharewhite.fcm.PopupConstObject.popup_package_count
import com.base.locationsharewhite.fcm.PopupConstObject.popup_package_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

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 {
            val popupPackageCount = AppPreferences.getInstance().getString(popup_package_count, "20").toInt()
            val flag1 = todayPackagePush <= popupPackageCount

            val minute = 60 * 1000L
            val default = 1 * minute
            val interval = AppPreferences.getInstance().getString(popup_package_interval, default.toString()).toLong()
            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(where: String, actionId: String) {
            if (where == POPUP_WHERE_PACKAGE) {
                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) {
            NotificationUiUtil.sendNotificationIfCan(context, POPUP_WHERE_PACKAGE)
        }

    }
}