import { IS_DEBUG } from "./Contants";
import * as schedule from 'node-schedule'
import { Container } from "typescript-ioc";
import { logger } from "mslib";
import { ApiError } from "./Errors";

/**
 * Cron表达式
 */
export class CronExpression {
    /**
     * 每{seconds}秒
     */
    static everySecondsOn(seconds) {
        return `*/${seconds} * * * * ?`;
    }

    /**
     * 每{minutes}分钟
     */
    static everyMinutesOn(minutes) {
        return `0 */${minutes} * * * ?`;
    }

    /**
     * 每{hours}小时
     */
    static everyHoursOn(hours) {
        return `0 0 */${hours} * * ?`;
    }

    /**
     * 每天{clock}点
     */
    static everyClockOn(clock) {
        return `0 0 ${clock} * * ?`;
    }
}

/**
 * Cron计划任务
 * 
 * 非DEBUG环境下启用计划任务
 * 
 * @param cronExpression cron时间表达式
 * @param description 计划任务描述,仅为记录日志
 * @returns 
 */
export function CronJob(cronExpression: string, description?: string): ClassDecorator {
    return function (target: Function) {
        if (IS_DEBUG) return;

        schedule.scheduleJob(cronExpression, async () => {
            try {
                let service = Container.get(target);
                await service.doService();
            } catch (error) {
                logger.error(`${description || '定时任务'}'${target.name}'出现异常\n>>>>>`, error instanceof ApiError ? error.toString() : error);
            }
        });

        logger.info(`${target.name}(${cronExpression}) ${description || ''}`);
    }
}