import { AbstractBacker } from "./execute-file-backers/abstruct-backer.js";
import { profiler, TextlintResult } from "@textlint/kernel";

/**
 * The maximum number of files in process at the same time.
 * Linting uses one thread, so more files at the same time do not finish earlier;
 * they only keep more file contents and syntax trees alive, and the garbage collector has to copy them.
 * So the next file starts when the file in process is finished.
 * Only when the files in process wait for something outside JavaScript, such as a network request of a rule,
 * another file starts, up to this number.
 */
const MAX_CONCURRENT_FILES = 8;
/**
 * The number of files in process at the same time while the profile is on.
 * The profile measures the phases of a file across `await`.
 * With more than one file, the time of a phase would include the work of the other files.
 */
const MAX_CONCURRENT_FILES_ON_PROFILE = 1;

export class ExecuteFileBackerManager {
    private _backers: AbstractBacker[];

    /**
     * create MessageProcessManager with backers
     * @param {AbstractBacker[]} backers
     */
    constructor(backers: AbstractBacker[] = []) {
        this._backers = backers;
    }

    /**
     * @param {AbstractBacker} backer
     */
    add(backer: AbstractBacker) {
        this._backers.push(backer);
    }

    /**
     * @param {AbstractBacker} backer
     */
    remove(backer: AbstractBacker) {
        const index = this._backers.indexOf(backer);
        if (index !== -1) {
            this._backers.splice(index, 1);
        }
    }

    /**
     * process `messages` with registered processes
     *
     * A file is in process at a time, in the order of `files`.
     * While the files in process wait for something outside JavaScript, another file starts,
     * and at most MAX_CONCURRENT_FILES files are in process at the same time.
     * While the profile is on, one file is in process at a time.
     * The results have the executed files in the order of `files`, and then the un-executed files.
     */
    async process<R extends TextlintResult>(
        files: string[],
        executeFile: (filePath: string) => Promise<R>
    ): Promise<R[]> {
        const executeFiles: string[] = [];
        const unExecutedResults: R[] = [];
        for (const filePath of files) {
            const shouldExecute = this._backers.every((backer) => {
                return backer.shouldExecute({ filePath });
            });
            if (shouldExecute) {
                executeFiles.push(filePath);
            } else {
                // add fake unExecutedResults for un-executed file.
                unExecutedResults.push({
                    filePath,
                    messages: []
                } as TextlintResult as R);
            }
        }
        const results = new Array<R>(executeFiles.length);
        let nextIndex = 0;
        let failed = false;
        const maxConcurrentFiles = profiler.enabled ? MAX_CONCURRENT_FILES_ON_PROFILE : MAX_CONCURRENT_FILES;
        await new Promise<void>((resolve, reject) => {
            let inProcess = 0;
            let waitingCheck: NodeJS.Immediate | undefined;
            const hasNextFile = () => !failed && nextIndex < executeFiles.length;
            const startNextFile = () => {
                const index = nextIndex++;
                inProcess++;
                const onError = (error: unknown) => {
                    // do not start the next files when a file fails
                    failed = true;
                    clearImmediate(waitingCheck);
                    reject(error);
                };
                try {
                    executeFile(executeFiles[index])
                        .then((result) => {
                            this._backers.forEach((backer) => {
                                backer.didExecute({ result });
                            });
                            results[index] = result;
                            inProcess--;
                            onFinishFile();
                        })
                        .catch(onError);
                } catch (error) {
                    onError(error);
                }
            };
            /**
             * Promise callbacks run before the event loop continues.
             * So when the callback of setImmediate is called, every file in process waits for something
             * that the event loop brings, such as I/O or a timer. Then another file can use the waiting time.
             * When no file waits, the callback is not called until all files are finished,
             * and the files are processed one after another.
             */
            const checkWaitingLater = () => {
                if (waitingCheck !== undefined || !hasNextFile() || inProcess >= maxConcurrentFiles) {
                    return;
                }
                waitingCheck = setImmediate(() => {
                    waitingCheck = undefined;
                    if (hasNextFile() && inProcess < maxConcurrentFiles) {
                        startNextFile();
                        checkWaitingLater();
                    }
                });
            };
            const onFinishFile = () => {
                if (failed) {
                    return;
                }
                if (hasNextFile()) {
                    if (inProcess === 0) {
                        startNextFile();
                    }
                    checkWaitingLater();
                } else if (inProcess === 0) {
                    clearImmediate(waitingCheck);
                    resolve();
                }
            };
            onFinishFile();
        });
        // wait all resolved, and call afterAll
        this._backers.forEach((backer) => {
            backer.afterAll();
        });
        return results.concat(unExecutedResults);
    }
}
