const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WebpackShellPlugin = require('webpack-shell-plugin');

const outputDirectory = './dist';
module.exports.outputDirectory = outputDirectory;

module.exports.getOptimizations = function () {
    return {
        splitChunks: {
            cacheGroups: {
                commons: {
                    name: 'commons',
                    filename: 'js/commons-bundle.js',
                    chunks: 'initial',
                    // (the filename of the commons chunk)
                    minChunks: 2,
                }
            }
        }
    };
    // new webpack.optimize.CommonsChunkPlugin({
    //     name: 'vendor',
    //     filename: 'vendor-bundle.js',
    //     minChunks: function (module) {
    //         return (module.context || '').indexOf('node_modules') !== -1;
    //     }
    // }),
    // new webpack.optimize.CommonsChunkPlugin({
    //     // (the commons chunk name)
    //     name: 'commons',
    //     // (the filename of the commons chunk)
    //     filename: 'js/commons-bundle.js',
    //     minChunks: function(module, count) {
    //         // (Modules must be shared between 2 entries or be included by the globally-exposed-dependencies-bundle)
    //         return /*(module.context || '').indexOf('node_modules') === -1 && */count >= 2;
    //     },
    // }),
};

module.exports.getPlugins = function (env) {
    env = env || {};
    return [
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment\/min$/),
        new webpack.optimize.ModuleConcatenationPlugin(), // --display-optimization-bailout
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: '[name].tmp.css',
            // filename: (getPath) => {
            //     // output the css into the css directory instead of the js directory (where the bundles are)
            //     return 'css/' + getPath('[name].tmp.css').replace(/^js\//, '');
            // },
            // chunkFilename: "[id].css"
        }),
        new WebpackShellPlugin({
            dev: false,
            onBuildEnd:[
                'echo "Starting CSS Merging"',
                'node cssConcatenator.js ' + outputDirectory + ' global.tmp.css global.css ' + !!env.CSS_SOURCEMAPS,
                'node cssConcatenator.js ' + outputDirectory + ' !(global).tmp.css app.css ' + !!env.CSS_SOURCEMAPS,
            ]
        })
    ];
};
