"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleIntervalJob = void 0;
const Job_1 = require("../../common/Job");
const SimpleIntervalSchedule_1 = require("./SimpleIntervalSchedule");
class SimpleIntervalJob extends Job_1.Job {
    constructor(schedule, task, options = {}) {
        var _a;
        super(options.id);
        this.preventOverrun = (_a = options.preventOverrun) !== null && _a !== void 0 ? _a : true;
        this.schedule = schedule;
        this.task = task;
    }
    start() {
        const time = (0, SimpleIntervalSchedule_1.toMsecs)(this.schedule);
        // See https://github.com/kibertoad/toad-scheduler/issues/24
        if (time >= 2147483647) {
            throw new Error('Due to setInterval limitations, no intervals longer than 24.85 days can be scheduled correctly. Please create LongIntervalJob instead.');
        }
        // Avoid starting duplicates and leaking previous timers
        if (this.timer) {
            this.stop();
        }
        if (this.schedule.runImmediately) {
            this.task.execute();
        }
        this.timer = setInterval(() => {
            if (!this.task.isExecuting || !this.preventOverrun) {
                this.task.execute();
            }
        }, time);
    }
    stop() {
        if (!this.timer) {
            return;
        }
        clearInterval(this.timer);
        this.timer = undefined;
    }
    getStatus() {
        if (this.timer) {
            return Job_1.JobStatus.RUNNING;
        }
        return Job_1.JobStatus.STOPPED;
    }
}
exports.SimpleIntervalJob = SimpleIntervalJob;
//# sourceMappingURL=SimpleIntervalJob.js.map