var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');

var rimraf = require('rimraf');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';

module.exports = function (env = {}) {
    env = env || {};
    const SETTINGS = {
        API_URL: env.api_url || 'http://localhost:52281/v1',
        API_IDENTIFIER: env.api_id || "138659EBEBBF408AA1282D46EBDFBDC7"
    };
    const BRAND_NAME = env.brand_name || 'KNK';

    // wait for removing destination folder
    rimraf.sync(helpers.root('dist', BRAND_NAME));

    return webpackMerge(commonConfig, {
        devtool: 'source-map',

        output: {
            path: helpers.root('dist', BRAND_NAME),
            //publicPath: `/${BRAND_NAME}`,
            publicPath: `/`,
            filename: '[name].[hash].js',
            chunkFilename: '[id].[hash].chunk.js'
        },

        plugins: [
            new webpack.NoEmitOnErrorsPlugin(),
            // new webpack.optimize.DedupePlugin(),
            new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
                mangle: {
                    keep_fnames: true
                }
            }),
            new ExtractTextPlugin('[name].[hash].css'),
            new webpack.DefinePlugin({
                'process.env': {
                    'ENV': JSON.stringify(ENV)
                },
                'SETTINGS': JSON.stringify(SETTINGS)
            }),
            new webpack.LoaderOptionsPlugin({
                htmlLoader: {
                    minimize: false // workaround for ng2
                }
            })
        ]
    });
};
