package com.base.scanqr.fcm.alarm

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.job.JobService
import android.content.Context
import android.content.Intent
import com.base.scanqr.BuildConfig
import com.base.scanqr.fcm.work.RepeatingWorker.Companion.schedulePeriodicWork
import java.util.Calendar

object AlarmUtils {

    fun startAlarm(context: Context, hour: Int) {
//        context.startJob()
        //闹钟定时任务
        val alarmManager = context.getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            context, hour, Intent(context, AlarmReceiver::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        val hourOfDay = if (BuildConfig.DEBUG) 0 else 6
        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)

        val oneHour = 60 * 60 * 1000L
        var delay = oneHour * hour
        if (BuildConfig.DEBUG) {
            delay = 1 * 60 * 1000L
        }
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP, calendar.timeInMillis, delay, pendingIntent
        )
        schedulePeriodicWork(context)
    }
}