// Build configuration
import { CsxConfig, runArgs } from "./config";
import { logBundle } from './log-bundle';

// Rollup and plugins
import * as rollup from 'rollup';

/**
 * Build CSX
 * @param {CsxConfig} cfg - Configuration on how to build
 * @param {boolean} clean - Clean the dist and lib-dirs first
 * @returns {Promise<CsxConfig>}
 */
async function build(cfg, clean){
    let {src, dist, lib, root, sourceGlob} = cfg;
    root = root.from('');// This is a bug in @cerxes/host!
    
    // Clean host
    if(clean!==false){
        await Promise.all([
            dist.remove('', {recursive: true}),
            lib.remove('', {recursive: true}),
        ]);
        console.log("Output-dirs cleaned!");
    }
    
    let appStart = new Date();
    let sources = await src.glob(sourceGlob);
    let targets = cfg.configureTargets(sources);
    
    let builds = targets.map(async target=>{
        return await Promise.all(
            target.sources.map(async source=>{
                let bundle = await rollup.rollup(source.config);
                let written = await bundle.write(source.config.output);
                let stats = await root.stat(source.config.output.file);
                logBundle(root.relative(source.config.output.file), (new Date()).getTime()-appStart.getTime(), stats);
                return {bundle, written};
            })
        );
    })
    
    let results = await Promise.all(builds);
    
    console.log("CSX built");
    return results
}

// Execute self if script is run as entry (e.g. "node build.js")
if(require.main === module) {
    // Run !
    build(new CsxConfig());
}

