'use strict';
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const os = require('os');
const ini = require('ini');

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const WebpackConfig = require('webpack-config');
const BowerResolvePlugin = require("bower-resolve-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

const loadTranslations = require('../trl/load-translations');
const lookupVendorPoFiles = require('../trl/lookup-vendor-po-files');
const lookupSassIncludePaths = require('../loader/lookup-sass-include-paths');
const lookupAliasPaths = require('../loader/lookup-alias-paths');
const TrlPlugin = require("../trl/trl-plugin");
const fetchLanguages = require("../loader/fetch-languages");
const fetchKwfConfig = require("./fetch-kwf-config");

var extractCssPlugin = new ExtractTextPlugin("./[name].css");
const kwfConfig = fetchKwfConfig();

const langauges = fetchLanguages();

const configIni = ini.parse(fs.readFileSync('config.ini', 'utf-8'));
const webCodeLangauge = configIni.production.webCodeLanguage;
const uniquePrefix = configIni.production['application.uniquePrefix'];

const devBuild = !!process.env.KWF_BUILD_DEV;

let plugins = [
    new TrlPlugin({
        uniquePrefix: uniquePrefix,
        languages: langauges,
        webCodeLanguage: webCodeLangauge,
        translations: {
            web: loadTranslations(['trl/[language].po'], langauges),
            kwf: loadTranslations(lookupVendorPoFiles(), langauges),
        }
    }),
    extractCssPlugin,
    new webpack.DefinePlugin({
        KWF_BASE_URL: '__webpack_require__.KWF_BASE_URL'
    })
];
if (!devBuild) {
    plugins.push(new UglifyJSPlugin());
    plugins.push(new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    }));
}


module.exports = {
    //devtool: "source-map", // or "inline-source-map"
    output: {
        path: process.cwd()+"/build/assets",
        publicPath: (kwfConfig['webpack-dev-server-url'] ? kwfConfig['webpack-dev-server-url'] : '/') + "assets/build/",
        filename: '[name].js',
        chunkFilename: "[id].js",
        jsonpFunction: uniquePrefix+'webpackJsonp',
        pathinfo: devBuild //Include comments with information about the modules
    },
    module: {
        rules: [{
            test: /\.underscore\.tpl$/,
            loader: "underscore-template-loader",
            options: {
                engine: 'underscore'
            }
        },{
            enforce: 'post',
            test: /\.s?css$/,
            loader: extractCssPlugin.extract({
                use: {
                    loader: "css-loader",
                    options: {
                        minimize: !devBuild,
                        import: false
                    }
                },
                fallback: "style-loader"
            })
        },{
            enforce: 'post',
            test: /\.s?css$/,
            loader: "postcss-loader",
            options: {
                plugins: function() {
                    return [
                        require('autoprefixer')({
                            browsers: '> 0.05%',
                            remove: true,
                            add: true
                        })
                    ];
                }
            }
        },{
            enforce: 'post',
            test: /\.(s?css|underscore\.tpl|jsx?)$/,
            loader: path.resolve(__dirname, "../loader/kwfup-loader")+"?uniquePrefix="+uniquePrefix,
        },{
            enforce: 'post',
            test: /vendor\/koala-framework\/extjs2\/.*\.css$/,
            loader: require.resolve('../loader/ext2-css-loader')

        }, {
            enforce: 'post',
            test: /\.scss$/,
            loader: "sass-loader",
            options: {
                includePaths: lookupSassIncludePaths(),
                data: "@import \"config/global-settings\";"
            }
            /*
             },{
             enforce: 'post',
             test: /\.scss$/,
             use: [{
             loader:  require.resolve('../loader/caching-loader') //to avoid same scss getting built twice when extractCssPlugin is used
             }, {
             loader: "sass-loader",
             options: {
             includePaths: lookupSassIncludePaths(),
             data: "@import \"config/global-settings\";"
             }
             }]
             */

        }, {
            test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
            loader: 'file-loader',
            options: {
                publicPath: (kwfConfig['webpack-dev-server-url'] ? kwfConfig['webpack-dev-server-url'] : '/') + "assets/build/",
                name: '[path][name].[ext]'
            }
        }]
    },
    resolve: {
        modules: ["node_modules", "vendor/bower_components"],
        descriptionFiles: ['package.json', 'bower.json'],
        mainFields: ['browser', 'module', 'main'],
        plugins: [new BowerResolvePlugin()],
        alias: lookupAliasPaths(),
        extensions: ['.js', '.json']
    },
    resolveLoader: {
        modules: ["node_modules", "vendor/koala-framework/koala-framework/node_modules_build"]
    },
    stats: {
        children: false
    },
    plugins: plugins,
    devServer: {
        disableHostCheck: true,
        stats: {
            children: false
        },
        proxy: {
            '/assets': {
                target: kwfConfig['webpack-dev-server-proxy'],
                secure: false,
                changeOrigin: true
            }
        },
        setup: function(app) {
            app.use(function (req, res, next) {
                //required for fonts loaded thru proxy
                res.setHeader("Access-Control-Allow-Origin", "*");
                next();
            });
        }
    }
};

@@ -2184,16 +2184,30 @@
 %22%5Bid%5D.js
+?v=%5Bchunkhash%5D
 %22,%0A     

Add chunkhash parameter to chunkFilename for cache-busting