const path = require('path');
const webpack = require('webpack');
const glob = require('glob');

function getMultPages() {
    const defaultTemplate = 'public/index.html';
    const enteies = {};
    const apps = glob.sync('src/apps/**/main.js');
    apps.forEach(path => {
        const reg = /\/(\w+)\/main.js$/.exec(path);
        if (reg && reg[1]) {
            const tem = glob.sync(`src/apps/${reg[1]}/index.html`);
            const name = reg[1].toLowerCase();
            enteies[name] = {
                entry: path,
                template: tem.length ? tem[0] : defaultTemplate,
                filename: `${process.env.NODE_ENV === 'development' ? `${name}/` : ''}index.html`,
                title: name,
            };
        }
    });
    return enteies;
}

function filterPages(pages) {
    if (process.env.NODE_ENV === 'development') {
        if (process.env.VUE_APP_LOCAL_ENV && process.env.VUE_APP_LOCAL_ENV !== '*') {
            const apps = process.env.VUE_APP_LOCAL_ENV.toLowerCase();
            Object.keys(pages).forEach(key => {
                if (!apps.includes(key)) {
                    delete pages[key];
                }
            });
        }
    } else {
        const buildApp = process.argv.slice(2)[1];
        if (pages[buildApp]) {
            pages = { [buildApp]: pages[buildApp] };
        }
    }
    return pages;
}

let pages = filterPages(getMultPages());

module.exports = {
    baseUrl: process.env.VUE_APP_BUILD_BASE_URL,
    pages,
    outputDir: path.join('dist', process.env.NODE_ENV === 'development' ? '' : Object.keys(pages)[0]),
    configureWebpack: {
        performance: {
            maxEntrypointSize: 512000,
            maxAssetSize: 1024000,
        },
    },
    chainWebpack: config => {
        Object.keys(pages).forEach(name => {
            // config.plugins.delete(`preload-${name}`);
            config.plugins.delete(`prefetch-${name}`);
            config.plugin('provide').use(
                new webpack.ProvidePlugin({
                    t: [path.join(__dirname, 'src/commonutils/test'), 'default'],
                })
            );
        });
    },
    css: {
        sourceMap: false,
        loaderOptions: {
            stylus: {
                import: [path.join(__dirname, 'src/assets/css/fun.styl')],
            },
        },
    },
    devServer: {
        overlay: {
            warnings: false,
            errors: true,
        },
        disableHostCheck: true,
        host: '0.0.0.0',
        port: 8081,
        proxy: {
            '/api': {
                target: process.env.VUE_APP_MOBILE_API_BASE_URL,
                changeOrigin: true,
                // pathRewrite: {
                //     '^/api': ''
                // }
            },
        },
        historyApiFallback: {
            rewrites: Object.keys(pages).map(name => {
                const re = new RegExp(`^/${name}/(?!.*\\.\\w+)`);
                const obj = {
                    from: new RegExp(`^/${name}`),
                    to(context) {
                        return re.test(context.parsedUrl.path) ? `/${name}` : context.parsedUrl.path;
                    },
                };
                return obj;
            }),
        },
    },
};
