package com.example.iot_controlhost.utils.timer;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.MyApp;
import com.example.iot_controlhost.receiver.TimerReceiver;
import com.example.iot_controlhost.utils.log.MyLog;

import java.util.Calendar;
import java.util.Date;

/**
 * 每日定时任务工具类
 */
public class TimerTaskUtil {
    /**
     * 每日启动时间-小时
     */
    private static final int DAILY_TIMER_HOUR = 0;
    /**
     * 每日启动时间-分钟
     */
    private static final int DAILY_TIMER_MINUTE = 30;
    /**
     * 请求码
     */
    private static final int REQUEST_CODE_DAILY_TIMER = 85412;

    /**
     * 开始自动任务
     *
     * @return 当前是否应该为亮色调（当前时间是否在日出和日落之间）
     */
    public static void start() {
        //设定新计划前先清除旧计划
        MyLog.auto("定时任务：正在重置每日定时任务");
        stop();
        Context context = MyApp.getAppContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, TimerReceiver.class);
        // 设置定时时间
        Calendar openCalendar = Calendar.getInstance();
        openCalendar.set(Calendar.HOUR_OF_DAY, DAILY_TIMER_HOUR);
        openCalendar.set(Calendar.MINUTE, DAILY_TIMER_MINUTE);
        openCalendar.set(Calendar.SECOND, 0);
        // 如果开启时间在当前时间之前
        if (openCalendar.before(Calendar.getInstance())) {
            MyLog.auto("定时任务：计划在当前时间之前，将时间设定为明天的同一时间");
            openCalendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        long openTimeInMillis = openCalendar.getTimeInMillis();
        MyLog.auto("定时任务：" + TimeUtils.date2String(new Date(openTimeInMillis)) + "时刷新每日计划");
        intent.setAction(TimerReceiver.DAILY_TIMER);
        PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_DAILY_TIMER, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, openTimeInMillis, AlarmManager.INTERVAL_DAY, openPendingIntent);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, openTimeInMillis, openPendingIntent);
    }

    /**
     * 关闭定时任务
     */
    private static void stop() {
        Context context = MyApp.getAppContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, TimerReceiver.class);
        PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_DAILY_TIMER, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(openPendingIntent);
    }

}
