"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const compiler_1 = require("../compiler");
const path_1 = require("path");
const resolve_dependencies_1 = require("resolve-dependencies");
const util_1 = require("../util");
function getStdIn(stdin) {
    let out = '';
    return new Promise((resolve) => {
        stdin
            .setEncoding('utf8')
            .on('readable', () => {
            let current;
            while ((current = stdin.read())) {
                out += current;
            }
        })
            .on('end', () => resolve(out.trim()));
        setTimeout(() => {
            if (!out.trim()) {
                resolve(out.trim());
            }
        }, 1000);
    });
}
function bundle(compiler, next) {
    return __awaiter(this, void 0, void 0, function* () {
        const { bundle: doBundle, cwd, input: inputPath } = compiler.options;
        let input = inputPath;
        compiler.entrypoint = './' + (0, path_1.relative)(cwd, input);
        if ((0, util_1.semverGt)(compiler.target.version, '11.99')) {
            compiler.startup = '';
        }
        else {
            compiler.startup = ';require("module").runMain();';
        }
        if (!doBundle) {
            yield compiler.addResource((0, path_1.resolve)(cwd, input));
            return next();
        }
        let code = '';
        if (typeof doBundle === 'string') {
            code = yield require(doBundle).createBundle(compiler.options);
        }
        if (input === util_1.STDIN_FLAG && (code = code || (0, util_1.dequote)(yield getStdIn(process.stdin)))) {
            compiler.stdinUsed = true;
            compiler.entrypoint = './__nexe_stdin.js';
            yield compiler.addResource((0, path_1.resolve)(cwd, compiler.entrypoint), code);
            return next();
        }
        if (input === util_1.STDIN_FLAG) {
            const maybeInput = (0, resolve_dependencies_1.resolveSync)(cwd, '.');
            if (!maybeInput || !maybeInput.absPath) {
                throw new compiler_1.NexeError('No valid input detected');
            }
            input = maybeInput.absPath;
            compiler.entrypoint = './' + (0, path_1.relative)(cwd, input);
        }
        const { files, warnings } = (0, resolve_dependencies_1.default)(input, ...Object.keys(compiler.bundle.list).filter((x) => x.endsWith('.js')), { cwd, expand: 'variable', loadContent: false });
        if (warnings.filter((x) => x.startsWith('Error parsing file') && !x.includes('node_modules')).length) {
            throw new compiler_1.NexeError('Parsing Error:\n' + warnings.join('\n'));
        }
        //TODO: warnings.forEach((x) => console.log(x))
        yield Promise.all(Object.entries(files).map(([key, file]) => {
            return compiler.addResource(key, file);
        }));
        return next();
    });
}
exports.default = bundle;
