package com.njzscloud.common.sichen.support;

import com.njzscloud.common.sichen.contant.ScheduleType;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.util.Date;

@Slf4j
public final class TaskUtil {
    public static long computedNextTiming(long now, TaskInfo taskInfo) {
        return computedNextTiming(now, taskInfo.getScheduleType(), taskInfo.getScheduleConf());
    }

    public static long computedNextTiming(TaskInfo taskInfo) {
        return computedNextTiming(System.currentTimeMillis() / 1000, taskInfo.getScheduleType(), taskInfo.getScheduleConf());
    }

    public static long computedNextTiming(ScheduleType scheduleType, String scheduleConf) {
        return computedNextTiming(System.currentTimeMillis() / 1000, scheduleType, scheduleConf);
    }

    public static long computedNextTiming(long now, ScheduleType scheduleType, String scheduleConf) {
        switch (scheduleType) {
            case Fixed:
                return new Date(now * 1000 + Long.parseLong(scheduleConf) * 1000L).getTime() / 1000;
            case Cron:
                try {
                    return new CronExpression(scheduleConf)
                            .getNextValidTimeAfter(new Date(now * 1000))
                            .getTime() / 1000;
                } catch (ParseException e) {
                    log.error("任务调度表达式解析错误", e);
                    return 0;
                }
        }
        return 0;
    }
}
