"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileSample = exports.compileSingle = exports.Options = void 0;
const common = __importStar(require("./common"));
const phases_1 = __importStar(require("./phases"));
// we need the path to lib so the code works in normal compile and in parcel
const Parser = require("../../lib/compiler/parser");
const watchDirectory_1 = __importDefault(require("./watchDirectory"));
const toModuleFiles_1 = __importStar(require("./phases/toModuleFiles"));
const NullLogger = () => { };
class Options {
    constructor(inputs, output, namespace, debug, emit) {
        var _a, _b;
        if (namespace === void 0) { namespace = (_b = (_a = common.findPackage()) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : "_compiling_"; }
        if (debug === void 0) { debug = true; }
        if (emit === void 0) { emit = true; }
        this.commandLine = false;
        this.namespace = namespace;
        this.inputs = inputs;
        this.output = output;
        this.debug = debug;
        this.emit = emit;
        this.errors = [];
    }
    static from(options) {
        if (options instanceof Options) {
            return options;
        }
        return new Options(options.inputs || [], options.output || "", options.namespace, options.debug || false, options.emit || (options.output != null && options.output.length > 0));
    }
}
exports.Options = Options;
function compileSingle(source, debug = true, name = "sample", ext = ".js") {
    let output = compileSample(source, name, debug, ext);
    if (typeof output === 'string') {
        return { output };
    }
    else {
        return { error: output };
    }
}
exports.compileSingle = compileSingle;
function compileSample(text, name = "sample", debug = true, ext = toModuleFiles_1.moduleExtension) {
    let emit = false;
    let compiler = new Compiler(() => { });
    let options = new Options([], "null", "none", debug, emit);
    let results = compiler.compile(options, { [name]: text });
    if (results.errors.length > 0) {
        return results.errors[0];
    }
    let output = results.phases.get(toModuleFiles_1.default).modules.get(name + ext);
    return output;
}
exports.compileSample = compileSample;
class Compiler {
    constructor(logger = () => { }) {
        this.logger = logger;
    }
    watch(optionsOrJson) {
        let options = Options.from(optionsOrJson);
        //  first compile normal
        this.compile(options);
        //  then watch files for changes
        for (let input of options.inputs) {
            watchDirectory_1.default(input, {}, (filename, previous, current, change) => {
                //  incrementally recompile just this file
                let start = Date.now();
                let content = common.read(filename);
                let path = common.getPathFromFilename(options.namespace, filename.slice(input.length + 1));
                // console.log({ filename, change, path, content })
                //  we *really* should also kickoff a full recompile in a separate thread
                //  or maybe the fast compile should be in the other thread
                // always reset options errors
                options.errors.length = 0;
                this.compile(options, { [path]: content }, phases_1.default, NullLogger);
                let stop = Date.now();
                let time = stop - start;
                console.log(`${filename} => ${time}ms`);
            });
        }
    }
    compile(optionsOrJson, files, phases = undefined, logger = this.logger) {
        let options = Options.from(optionsOrJson);
        if (phases == null) {
            phases = options.emit ? phases_1.default : phases_1.noEmit;
        }
        options.parser = Parser();
        if (files == null) {
            files = common.getInputFilesRecursive(options.inputs, options.namespace);
        }
        function printErrorConsole(e) {
            let location = e.location;
            if (location == null || location.start == null) {
                throw e;
            }
            else {
                let { filename } = location;
                let source = files === null || files === void 0 ? void 0 : files[filename];
                let error = options.parser.getError(e.message, location, source, filename);
                console.log("");
                console.log(error.message.trim());
            }
        }
        let errors = options.errors;
        let phaseResults = new Map();
        let root = files;
        logger("Input", root);
        let lastPhase;
        try {
            for (let phase of phases) {
                // console.log(phase.name)
                lastPhase = phase;
                let before = errors.length;
                root = phase(root, options) || root;
                let after = errors.length;
                let count = after - before;
                if (count > 0) {
                    console.log(phase.name + ": Errors: " + count);
                }
                phaseResults.set(phase, root);
                logger(phase.name, root);
            }
            logger("Output", root);
            logger();
        }
        catch (e) {
            logger();
            errors.push(e);
            if (options.commandLine) {
                console.log(lastPhase === null || lastPhase === void 0 ? void 0 : lastPhase.name);
                printErrorConsole(e);
                console.log("");
            }
        }
        if (options.errors.length > 0) {
            for (let e of options.errors) {
                printErrorConsole(e);
            }
            console.log("");
        }
        return { phases: phaseResults, errors };
    }
}
exports.default = Compiler;
