const webpack = require('webpack');

exports.build = function () {
    return Promise.all([
        //JSNative
        new Promise(function (resolve, reject) {
            if(require("./lib/utils").hasPlugin("jsnative") && (!light.options.onlyFor || light.options.onlyFor === 'jsn')){
                let config_native = require("./build.native").build();
                return webpack(config_native, function (err, stats) {
                    /*mark: node埋点*/
                    try {
                        light.gio.emit('gio_event', {
                            time: new Date().getTime()
                        })
                        light.gio.removeAllListeners(['gio_event'])
                    } catch(err){
                    }
                    if (err || (stats && stats.hasErrors())) {
                        reject();
                    }
                    resolve();
                })
            }else{
                resolve()
            }
        }),
        //miniapp
        new Promise(function (resolve, reject) {
            if(require("./lib/utils").hasPlugin("miniapp") && (!light.options.onlyFor || light.options.onlyFor === 'miniapp')){
                let config_native = require("./build.miniapp").build();
                // 【小程序】小程序在编译构建时支持热刷新功能，当开发者编辑代码后大约5s左右触发手机端程序界面的自动加载刷新
                global.middleware = global.middleware || [];
                let clinetCheckMap = {};
                global.middleware.push(function(req,res,next){
                    if(req.path === "/check_reload_me"){
                        if(!clinetCheckMap[req.query.id]){
                            clinetCheckMap[req.query.id] = false;
                        }
                        res.send({
                            reload:clinetCheckMap[req.query.id]
                        })
                        clinetCheckMap[req.query.id] = false;
                    }else{
                        next()
                    }
                });
                return webpack(config_native, function (err, stats) {
                    Object.keys(clinetCheckMap).forEach(client=>{clinetCheckMap[client]=true});
                    
                    /*mark: node埋点*/
                    try {
                        light.gio.emit('gio_event', {
                            time: new Date().getTime()
                        })
                        light.gio.removeAllListeners(['gio_event'])
                    } catch(err) {}
                    if (err || (stats && stats.hasErrors())) {
                        reject();
                    }
                    resolve();
                })
            }else{
                resolve()
            }
        }),
        //web
        new Promise(function (resolve, reject) {
            //110579：若--only-for jsn，则不编译h5、harmony，harmony编译与h5一致，但增加了platform标识，用于web技术实现的鸿蒙app
            if (light.options.onlyFor &&  light.options.onlyFor !== 'h5' && light.options.onlyFor !== 'harmony') {
               return resolve()
            }

            let config_web = require("./build.web").build();
            if (light.options.watch) {
                // 这里加了回调会直接进行编译，与webpack-dev-middleware存在冲突
                const compiler = webpack(config_web);
                
                //122625 【TS:201902110033-财富业委会-潘腾-【需求类型】	需求【需求描述】	1. 前后端分离开发】
                global.middleware = global.middleware || [];

                const devModule = require("webpack-dev-middleware")(compiler, {
                    // logLevel: 'warn' // 这里可以屏蔽警告以下的日志，暂留
                });
                global.middleware.push(devModule);

                devModule.waitUntilValid((stats) => {
                    // 若工程为Jsn 此处不进入上报逻辑 会造成jsn工程初次启动时页面报错白屏
                    if(!require("./lib/utils").hasPlugin("jsnative")) {
                        /*mark: node埋点*/
                        try {
                            light.gio.emit('gio_event', {
                                time: new Date().getTime()
                            })
                            light.gio.removeAllListeners(['gio_event'])
                        } catch(err) {}
                    }
                    if (stats && stats.hasErrors()) {
                        reject();
                    }
                    resolve();
                });

                // webpack3必须配置热更新中间件，v4及以上版本通过配置hot可自动启用热更新
                global.middleware.push(require("webpack-hot-middleware")(compiler, {
                    // noInfo: true, log: false
                }))
            } else {
                webpack(config_web, function (err, stats) {
                    /*mark: node埋点*/
                    try {
                        light.gio.emit('gio_event', {
                            time: new Date().getTime()
                        })
                        light.gio.removeAllListeners(['gio_event'])
                    } catch(err){
                    }
                    if (err || (stats && stats.hasErrors())) {
                        reject();
                    }
                    resolve();
                });
            }
        }),
        //230279 light-sdk支持全局JSCore
        new Promise(function (resolve, reject) {
            let gmuGlobalJS = require("path").join(light.config.src, "gmu.global.js");
            if (require("fs").existsSync(gmuGlobalJS)) {
                let config_globalJscore = require("./build.globalJscore").build();
                return webpack(config_globalJscore, function (err, stats) {
                    if (err || (stats && stats.hasErrors())) {
                        reject();
                    }
                    resolve();
                })
            } else {
                return resolve()
            }
        })
    ])
};
