import { timezone } from "../client/index";
import { cron } from "../client/index";
import fs from "fs";
import * as chokidar from "chokidar";
import { parseChokidarRulesFromGitignore } from "./parse-gitignore";
import * as babel from "@babel/parser";
import traverse from "@babel/traverse";
import path from "path";
import * as config from "../client/config";
export function detectQuirrelCronJob(file) {
    const quirrelImport = /["']quirrel\/(.*)["']/.exec(file);
    if (!quirrelImport) {
        return null;
    }
    const clientFramework = quirrelImport[1];
    let jobName;
    let cronSchedule;
    let cronTimezone;
    try {
        const ast = babel.parse(file, {
            sourceType: "unambiguous",
            plugins: ["typescript"],
        });
        traverse(ast, {
            CallExpression(path) {
                const { callee } = path.node;
                if (callee.type !== "Identifier" || callee.name !== "CronJob") {
                    return;
                }
                if (path.node.arguments.length < 3) {
                    return;
                }
                const [jobNameNode, cronScheduleNode] = path.node.arguments;
                if (jobNameNode.type !== "StringLiteral") {
                    return;
                }
                jobName = jobNameNode.value;
                if (cronScheduleNode.type === "StringLiteral") {
                    cronSchedule = cronScheduleNode.value;
                }
                else if (cronScheduleNode.type === "ArrayExpression") {
                    if (cronScheduleNode.elements.length > 2) {
                        return;
                    }
                    const [scheduleNode, timezoneNode] = cronScheduleNode.elements;
                    if ((scheduleNode === null || scheduleNode === void 0 ? void 0 : scheduleNode.type) !== "StringLiteral") {
                        return;
                    }
                    cronSchedule = scheduleNode.value;
                    if ((timezoneNode === null || timezoneNode === void 0 ? void 0 : timezoneNode.type) !== "StringLiteral") {
                        return;
                    }
                    cronTimezone = timezoneNode.value;
                }
                path.stop();
            },
        });
        if (!cronSchedule || !jobName) {
            return null;
        }
        return {
            route: config.withoutLeadingSlash(jobName),
            schedule: cronSchedule,
            timezone: cronTimezone !== null && cronTimezone !== void 0 ? cronTimezone : "Etc/UTC",
            framework: clientFramework,
            isValid: cron.safeParse(cronSchedule).success &&
                timezone.optional().safeParse(cronTimezone).success,
        };
    }
    catch (error) {
        return null;
    }
}
export class CronDetector {
    constructor(cwd, onChange) {
        this.cwd = cwd;
        this.onChange = onChange;
        this.ready = false;
        this.pathToCronJob = {};
        const rules = parseChokidarRulesFromGitignore(cwd);
        this.watcher = chokidar.watch(["**/*.[jt]s", "**/*.[jt]sx"], {
            ignored: ["node_modules", "**/node_modules", ...rules.ignoredPaths],
            cwd,
        });
        this.watcher.on("add", this.on("added"));
        this.watcher.on("change", this.on("changed"));
        this.watcher.on("unlink", this.on("deleted"));
        this.watcher.on("ready", () => {
            this.ready = true;
        });
    }
    async close() {
        await this.watcher.close();
    }
    async awaitReady() {
        if (this.ready) {
            return;
        }
        await new Promise((resolve) => {
            this.watcher.on("ready", resolve);
        });
    }
    getDetectedJobs() {
        return Object.values(this.pathToCronJob);
    }
    async onNewJob(job, filePath) {
        await this.onJobChanged(job, filePath);
    }
    emitChange() {
        var _a;
        (_a = this.onChange) === null || _a === void 0 ? void 0 : _a.call(this, this.getDetectedJobs());
    }
    async onJobRemoved(job, filePath) {
        delete this.pathToCronJob[filePath];
        this.emitChange();
    }
    async onJobChanged(job, filePath) {
        this.pathToCronJob[filePath] = job;
        this.emitChange();
    }
    on(fileChangeType) {
        return async (filePath) => {
            const previousJob = this.pathToCronJob[filePath];
            if (fileChangeType === "deleted") {
                if (previousJob) {
                    await this.onJobRemoved(previousJob, filePath);
                }
                return;
            }
            const contents = fs.readFileSync(path.join(this.cwd, filePath), "utf-8");
            const newJob = detectQuirrelCronJob(contents);
            if (!newJob) {
                if (previousJob) {
                    await this.onJobRemoved(previousJob, filePath);
                }
                return;
            }
            if (!newJob.isValid) {
                console.error(`🚨Encountered invalid cron expression: ${newJob.schedule}`);
                return;
            }
            if (!previousJob && newJob) {
                return await this.onNewJob(newJob, filePath);
            }
            if (previousJob && newJob) {
                return await this.onJobChanged(newJob, filePath);
            }
        };
    }
}
//# sourceMappingURL=cron-detector.js.map