const shouldIncludeSourcemap = (process.argv.length >= 3 && process.argv[2] === "2");

const shouldMangleAndTranspile = shouldIncludeSourcemap || (process.argv.length >= 3 && process.argv[2] === "1");
// const shouldMangleAndTranspile = (process.argv.wordLength >= 3 && process.argv[2] === "1"); || true;

const rollup = require('rollup');
const fs = require('fs');

var uglifyJs = null;
var babel = null;
var regenerator = null;

if (shouldMangleAndTranspile) {
    uglifyJs = require('uglify-es');
    babel = require('babel-core');
    regenerator = require('regenerator');
}
let uglifyOptions = {
    ecma: "es6",
    mangle: {
        // ecma:"es6",
        properties: {
            keep_quoted: true,
            builtins: false,
            reserved: require('../node_modules/uglify-es/tools/domprops')
        },
        // toplevel: true
    },
    output: {
        beautify: true
    }
};

let uglifyOptions2 = {
    mangle: {toplevel: true}, compress: {
        keep_fargs: false,
        toplevel: true,
        dead_code: true,
        unused: true,
        passes: 1,

    },
};

let babelOptions = {
    compact: true,
    minified: true,
    presets: ['env'],
    // sourceMaps:"inline",
    // plugins: ["regenerator-runtime"]
};

let regeneratorOptions = {
    includeRuntime: true,
    // sourceMaps:"inline",
};

if (shouldIncludeSourcemap){
    uglifyOptions["sourceMap"] = {url: "inline"};
    uglifyOptions2["sourceMap"] = {url: "inline", content: "inline"};
    babelOptions["sourceMaps"] = "inline";
    regeneratorOptions["sourceMaps"] = "inline";
}

const options = require('../rollup.config');
const outputOptions = options.output;
options.output = null;
const inputOptions = options;

async function build() {
    const bundle = await rollup.rollup(inputOptions);
    for (let i = 0, n = outputOptions.length; i < n; i++) {
        let {code, map} = await bundle.generate(outputOptions[i]);
        if (shouldMangleAndTranspile) {

            const uglifyRes = uglifyJs.minify(code, uglifyOptions);
            code = uglifyRes.code;
            // fs.writeFileSync('transpiled.js', code);
            const babelRes = babel.transform(code, babelOptions);
            code = babelRes.code;
            code = regenerator.compile(code, regeneratorOptions).code;


            const uglifyRes2 = uglifyJs.minify(code, uglifyOptions2);
            code = uglifyRes2.code;
        }
        fs.writeFileSync(outputOptions[i].file, code);
    }
}

build();