const { getAppConfig, pathResolve } = require('./utils.js');
const appConfig = getAppConfig();

const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const babelConfig = require("./config/babel.config.js");
babelConfig.babelrc = false;

const webpackConfig = {
    "entry": appConfig.entry,
    "output": {
        "path": pathResolve(appConfig.distPath),
        "filename": `${appConfig.fileName}${appConfig.hash ? `-[hash:${appConfig.hash}]` : ''}.js`,
        "chunkFilename": `${appConfig.fileName}${appConfig.hash ? `-[chunkhash:${appConfig.hash}]` : ''}.js`,
        "publicPath": appConfig.publicPath
    },
    "resolve": {
        "extensions": [".js", ".jsx"]
    },
    "plugins": [],
    "module": {
        "rules": [
            {
                "test": /\.jsx?$/,
                "use": {
                    "loader": "babel-loader",
                    "options": babelConfig
                }
            },
            {
                "test": /\.(png|jpg|jpeg|gif)(\?.*$)?$/i,
                "use": 'url-loader?limit=10000'
            }
        ]
    }
};

if (appConfig.extractAllCss) {
    if (appConfig.antd && !appConfig.antd.disable) {
        // 使用antd
    } else {
        const appCss = new ExtractTextPlugin({
            filename: `${appConfig.fileName}${appConfig.hash ? `-[contenthash:${appConfig.hash}]` : ''}.css`,
            disable: false,
            allChunks: true
        });
        const { getCssRule } = require("./cssUtils");
        webpackConfig.plugins.push(appCss);
        webpackConfig.module.rules.push(getCssRule(appCss, "css"));
        webpackConfig.module.rules.push(getCssRule(appCss, "less"));
    }
}

if (appConfig.html && !appConfig.html.disable) {
    delete appConfig.html.disable;
    const HtmlPlugin = require('html-webpack-plugin');
    webpackConfig.plugins.push(new HtmlPlugin(appConfig.html));
}

const isProd = (process.env.NODE_ENV || "").trim() === "production";
if (isProd) {
    const BabiliPlugin = require("babili-webpack-plugin");
    webpackConfig.plugins.push(new BabiliPlugin());
} else {
    webpackConfig.devServer = {
        "contentBase": appConfig.distPath,
        "host": appConfig.host,
        "port": appConfig.port,
        "hot": appConfig.hmr,
        "historyApiFallback": true,
        "disableHostCheck": true
    }
    if (appConfig.hmr) {
        webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
    }
}

module.exports = (getWebpackConfig) => {
    if (typeof getWebpackConfig === 'function') {
        return getWebpackConfig(webpackConfig, { appConfig, isProd, babelConfig });
    } else {
        return webpackConfig;
    }
};