//@ts-nocheck
import { rollup } from 'rollup';
import path from 'path';
import child_process from 'child_process';
import createRollupConfig from "./createRollupConfig";
import fs from "fs";
import COLORS from "./Constant";
import log from './logprint';
const { exec }  = child_process;
export default async function build(configPath:any) {

    if(configPath){
        const cmd = `rollup --config ${configPath}`;
        exec(cmd, function(error, stdout, stderr) {
            // 获取命令执行的输出
        });
        return;
    }
    let cfgfile = {};

    if(fs.existsSync(path.join(process.cwd(),'./.balarc'))){
        try {
            cfgfile =   JSON.parse(fs.readFileSync(path.join(process.cwd(),'./.balarc')).toString('utf-8'));
        } catch (e) {
            log.pretty('💥',`Sorry,小朋友，balarc格式是严格的JSON格式，请检查！\n${e}`,'danger')
            process.exit(0);
        }
    } else {
        cfgfile = {
            bundleType: 'split'
        }
    }
    if('single' === cfgfile.bundleType || 'all' === cfgfile.bundleType){
        console.log(COLORS.BRIGHT,'组件库单包，时间有点长，你先喝杯茶！');
        const singleCfg = createRollupConfig('single', cfgfile);
        try {
            const { output:outputOptions, watch, ...rest} = singleCfg[0];
            const bundle = await rollup(rest);
            outputOptions.map(async (v,k)=>{
                const { output } = await bundle.generate(v);
                // or write the bundle to disk
                const result = await bundle.write(v);
                console.log(COLORS.BRIGHT,'组件库单包',result.output[0].fileName,'Bundle成功！');
            });

        } catch (e) {
            log.pretty('💥',`组件库整体打包失败!\n${e}`,'danger')
            process.exit(0);
        }

    }
    if('split' === cfgfile.bundleType || 'all' === cfgfile.bundleType){
        console.log(COLORS.BRIGHT,'开始组件分包，时间有点长，你先喝杯茶！');
        const configList = createRollupConfig('split', cfgfile);

        configList.map(async (rollcfg,k)=>{
            const { output:outputOptions, watch, ...rest} = rollcfg;

            const bundle = await rollup(rest);

            outputOptions.map(async (v,k)=>{
                const { output } = await bundle.generate(v);

                for (const chunkOrAsset of output) {
                    if (chunkOrAsset.type === 'asset') {
                        //console.log('Asset', chunkOrAsset);
                    } else {
                        //console.log('Chunk', chunkOrAsset.modules);
                    }
                }

                // or write the bundle to disk
                const result = await bundle.write(v);
                console.log(COLORS.BRIGHT,'组件',result.output[0].fileName,'Bundle成功！');
            });

        });
    }
}
