package com.swiftcleaner.chovey.business.push

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.GlobalConfig.ID_APP_INSTALL
import com.swiftcleaner.chovey.GlobalConfig.ID_APP_UNINSTALL
import com.swiftcleaner.chovey.util.SPUtils
import com.swiftcleaner.chovey.util.Utils.toDate

class PackageReceiver : BroadcastReceiver() {

    companion object {
        private const val PACKAGE_NOTIFICATION_STATUS_KEY = "packageNotificationStatus"
        private const val PACKAGE_NOTIFICATION_INTERVAL_KEY = "packageNotificationInterval"
        private const val PACKAGE_NOTIFICATION_COUNT_KEY = "packageNotificationCount"
        private const val PACKAGE_NOTIFICATION_CURRENT_KEY = "packageNotificationCurrent"
        private const val PACKAGE_NOTIFICATION_LAST_TIME_KEY = "packageNotificationLastTime"

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

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action !in setOf(Intent.ACTION_PACKAGE_ADDED, Intent.ACTION_PACKAGE_REMOVED)) return

        val locks = SPUtils.getInstance().getInt(PACKAGE_NOTIFICATION_STATUS_KEY, 1)
        if (locks != 1) return

        val interval = SPUtils.getInstance().getInt(PACKAGE_NOTIFICATION_INTERVAL_KEY, 5) * 60 * 1000L
        val count = SPUtils.getInstance().getInt(PACKAGE_NOTIFICATION_COUNT_KEY, 100)

        val currentKey = "${PACKAGE_NOTIFICATION_CURRENT_KEY}_${context.toDate()}"
        val current = SPUtils.getInstance().getInt(currentKey)
        val lastTimeKey = "${PACKAGE_NOTIFICATION_LAST_TIME_KEY}_${context.toDate()}"
        val lastTime = SPUtils.getInstance().getLong(lastTimeKey, 0)
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastTime > interval && current < count) {
            val id = when (intent.action) {
                Intent.ACTION_PACKAGE_ADDED -> ID_APP_INSTALL
                Intent.ACTION_PACKAGE_REMOVED -> ID_APP_UNINSTALL
                else -> return
            }
            SPUtils.getInstance().putInt(currentKey, current + 1)
            SPUtils.getInstance().putLong(lastTimeKey, currentTime)
            NotificationUtils.sendNotification(CleanApplication.context, id, "app_receiver")
        }
    }
}