package io.wdd.rpc.scheduler.config;

import io.wdd.common.utils.TimeUtils;
import io.wdd.rpc.scheduler.beans.ScriptSchedulerDTO;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;

import static io.wdd.rpc.scheduler.beans.ScriptSchedulerVO.SCRIPT_SCHEDULE_MISSION_GROUP_NAME;

@Component
public class QuartzSchedulerUtils {

    @Resource
    private Scheduler scheduler;

    /**
     * @param scriptSchedulerDTO dto
     * @return dto中存储的 未来ExecutionKey对象
     */
    public  HashMap<String, String> generateAndSetFutureExecutionResultKey(ScriptSchedulerDTO scriptSchedulerDTO) {

        ArrayList<LocalDateTime> time = getLastNextExecutionTime(
                scriptSchedulerDTO.getSchedulerUuid(),
                SCRIPT_SCHEDULE_MISSION_GROUP_NAME
        );

        LocalDateTime nextExecutionTime = time.get(1);

        HashMap<String, String> keyMap = scriptSchedulerDTO.getAgentTopicNameToFutureResultKeyMap();

        // 为每一个目标Agent都要设置相应的 FutureKey
        scriptSchedulerDTO
                .getTargetMachineList()
                .stream()
                .forEach(
                        targetMachine -> {
                            keyMap.put(
                                    targetMachine,
                                    "todo 2023年8月14日"
                            );
                        }
                );

        return keyMap;
    }

    /**
     * 定时任务通常在将来执行，所以需要手动获取到下次的执行时间
     *
     * @param missionName      任务名称
     * @param missionGroupName 任务Group组名
     * @return 上次调度时间 下次执行时间
     */
    private ArrayList<LocalDateTime> getLastNextExecutionTime(String missionName, String missionGroupName) {
        // 获取JobDetail存储上次调度时间和下次执行时间
        try {
            Trigger schedulerTrigger = scheduler.getTrigger(
                    new TriggerKey(
                            missionName,
                            missionGroupName
                    )
            );

            ArrayList<LocalDateTime> result = new ArrayList<>();

            LocalDateTime last_schedule_time = TimeUtils.cvFromDate(schedulerTrigger.getFinalFireTime());
            LocalDateTime next_schedule_time = TimeUtils.cvFromDate(schedulerTrigger.getNextFireTime());

            result.add(last_schedule_time);
            result.add(next_schedule_time);

            return result;

        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }


}
