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.ThemeReceiver;
import com.example.iot_controlhost.utils.global.RoomSetting;
import com.example.iot_controlhost.utils.log.MyLog;
import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import com.luckycatlabs.sunrisesunset.dto.Location;

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

/**
 * 亮暗色调自动定时切换工具类
 */
public class ThemeTaskUtil {
    private static final int REQUEST_CODE_LIGHT = 62541;
    private static final int REQUEST_CODE_NIGHT = 96547;

    /**
     * 开始自动任务
     *
     * @return 当前是否应该为暗色调
     */
    public static boolean resetTask() {
        //设定新计划前先清除旧计划
        MyLog.auto("定时任务：正在重置亮暗色调定时任务");
        stop();
        double latitude = RoomSetting.getRoomCoordinateLatitude();
        double longitude = RoomSetting.getRoomCoordinateLongitude();
//       latitude = 27.07936;
//       longitude = 102.35740;
        Location location = new Location(latitude, longitude);
        // 创建日出日落计算器对象
        SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, TimeZone.getDefault());
        // 获取日出时间
        String sunrise = calculator.getOfficialSunriseForDate(Calendar.getInstance());
        // 获取日落时间
        String sunset = calculator.getOfficialSunsetForDate(Calendar.getInstance());

        // 解析日出时间的小时和分钟
        String[] sunriseParts = sunrise.split(":");
        int sunriseHour = Integer.parseInt(sunriseParts[0]);
        int sunriseMinute = Integer.parseInt(sunriseParts[1]);

        // 解析日落时间的小时和分钟
        String[] sunsetParts = sunset.split(":");
        int sunsetHour = Integer.parseInt(sunsetParts[0]);
        int sunsetMinute = Integer.parseInt(sunsetParts[1]);
        //测试时间
//        sunriseHour = 15;
//        sunriseMinute = 23;
//        sunsetHour = 15;
//        sunsetMinute = 20;

        Context context = MyApp.getAppContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, ThemeReceiver.class);

        // 设置亮色调的时间
        Calendar openCalendar = Calendar.getInstance();
        openCalendar.set(Calendar.HOUR_OF_DAY, sunriseHour);
        openCalendar.set(Calendar.MINUTE, sunriseMinute);
        openCalendar.set(Calendar.SECOND, 0);
        long openTimeInMillis = openCalendar.getTimeInMillis();
        MyLog.auto("定时任务：" + TimeUtils.date2String(new Date(openTimeInMillis)) + "时开启亮色调");
        // 如果开启时间在当前时间之前
        if (openCalendar.before(Calendar.getInstance())) {
//            MyLog.auto("定时任务：开启亮色调在当前时间之前，不设定亮色调开启时间");
        } else {
            intent.setAction(ThemeReceiver.THEME_LIGHT);
            PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_LIGHT, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, openTimeInMillis,  openPendingIntent);
        }
        // 设置暗色调的时间
        Calendar closeCalendar = Calendar.getInstance();
        closeCalendar.set(Calendar.HOUR_OF_DAY, sunsetHour);
        closeCalendar.set(Calendar.MINUTE, sunsetMinute);
        closeCalendar.set(Calendar.SECOND, 0);
        long closeTimeInMillis = closeCalendar.getTimeInMillis();
        MyLog.auto("定时任务：" + TimeUtils.date2String(new Date(closeTimeInMillis)) + "时开启暗模式");
        // 如果关闭时间在当前时间之前
        if (closeCalendar.before(Calendar.getInstance())) {
//            MyLog.auto("定时任务：开启暗色调在当前时间之前，不设定暗色调开启时间");
        } else {
            intent.setAction(ThemeReceiver.THEME_NIGHT);
            PendingIntent closePendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_NIGHT, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, closeTimeInMillis, closePendingIntent);
        }

        // 获取当前时间
        Calendar currentTime = Calendar.getInstance();
        int currentHour = currentTime.get(Calendar.HOUR_OF_DAY); // 获取当前小时
        int currentMinute = currentTime.get(Calendar.MINUTE); // 获取当前分钟
        // 判断当前时间是否在日出和日落之间（含边界）
        boolean isBeforeSunrise = currentHour < sunriseHour || (currentHour == sunriseHour && currentMinute < sunriseMinute);
        boolean isAfterSunset = currentHour > sunsetHour || (currentHour == sunsetHour && currentMinute >= sunsetMinute);

        return isBeforeSunrise || isAfterSunset;
    }
    /**
     * 关闭定时任务
     */
    private static void stop() {
        Context context = MyApp.getAppContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, ThemeReceiver.class);
        PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_LIGHT, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(openPendingIntent);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_NIGHT, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(closePendingIntent);
    }

}
