package com.example.iot_controlhost.utils.control.disinfect;

import com.example.iot_controlhost.model.MyTask;
import com.example.iot_controlhost.model.thread.QueueIOTask;
import com.example.iot_controlhost.utils.MyQueue;
import com.example.iot_controlhost.utils.MyUtil;
import com.example.iot_controlhost.utils.control.Control;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.log.MyLog;
import com.example.iot_controlhost.utils.timer.UVTaskUtil;

import java.util.Calendar;

/**
 * @Description 自动模式-控制逻辑-消毒灯
 * @Author DuanKaiji
 * @CreateTime 2023年11月09日 10:27:11
 */
public class DisinfectController extends Control {

    private static DisinfectController instance;

    public static DisinfectController getInstance() {
        if (instance == null) {
            synchronized (DisinfectController.class) {
                if (instance == null) {
                    instance = new DisinfectController();
                }
            }
        }
        return instance;
    }

    @Override
    protected boolean startMethod() {
        //初始化消毒定时任务
        MyLog.auto("初始化消毒定时任务");
        if (!RoomController.uvLight.isAvailable()) {
            return false;
        }
        //开始控制消毒任务时，先检查当前是否在消毒计划中
        boolean target = UVTaskUtil.getUvTask().stream().anyMatch(task ->
                isBetween(task.getStartTimeHour(), task.getStartTimeMinute(), task.getEndTimeHour(), task.getEndTimeMinute()));
        MyQueue.getInstance(MyQueue.TYPE_CONTROLLER).addTask(new QueueIOTask(() -> MyUtil.autoControlOperateThird(RoomController.uvLight, target)));
        for (MyTask task : UVTaskUtil.getUvTask()) {
            UVTaskUtil.stopTask(task);
        }
        for (MyTask task : UVTaskUtil.getUvTask()) {
            UVTaskUtil.startTask(task);
        }
        return true;
    }

    public static boolean isBetween(int startHour, int startMinute, int endHour, int endMinute) {
        // 获取当前时间
        Calendar currentTime = Calendar.getInstance();
        int currentHour = currentTime.get(Calendar.HOUR_OF_DAY);
        int currentMinute = currentTime.get(Calendar.MINUTE);

        // 计算开始时间和结束时间的总分钟数
        int startTimeInMinutes = startHour * 60 + startMinute;
        int endTimeInMinutes = endHour * 60 + endMinute;

        // 计算当前时间的总分钟数
        int currentTimeInMinutes = currentHour * 60 + currentMinute;

        // 检查当前时间是否在开始时间和结束时间之间
        return currentTimeInMinutes >= startTimeInMinutes && currentTimeInMinutes <= endTimeInMinutes;
    }

    @Override
    protected void stopMethod() {
        MyLog.auto("停止自动控制消毒————————————————————————————————————————————————————");
        for (MyTask task : UVTaskUtil.getUvTask()) {
            UVTaskUtil.stopTask(task);
        }
        //关闭消毒灯
        MyUtil.autoControlOperateThird(RoomController.uvLight);
    }
}
