package com.swiftcleaner.chovey.business.push

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.business.EventUtils
import com.swiftcleaner.chovey.util.SPUtils
import java.util.concurrent.TimeUnit

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        EventUtils.event("alarm_push")
        val firstAlarmTime = SPUtils.getInstance().getLong("firstAlarmTime")
        if (firstAlarmTime > 0) {
            val lastTime = System.currentTimeMillis()
            if (lastTime - firstAlarmTime >= 1000 * 30 * 60) {
                NotificationUtils.sendNotification(CleanApplication.context, "alarm")
                initWorkManager()
            }
        }
        SPUtils.getInstance().putLong("firstAlarmTime", System.currentTimeMillis())
    }

    private fun initWorkManager() {
        val tag = "${CleanApplication.context.packageName}_unique_periodic_work"
        val periodicRequest = PeriodicWorkRequestBuilder<MyWorker>(15, TimeUnit.MINUTES)
            .setConstraints(
                Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
            )
            .addTag(tag)
            .build()
        WorkManager.getInstance(CleanApplication.context).enqueueUniquePeriodicWork(
            tag,
            ExistingPeriodicWorkPolicy.KEEP,
            periodicRequest)
    }
}