const glob = require('glob');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const htmlPlugins = generateHtmlPlugins();

function generateHtmlPlugins() {
    
    const templateFiles = glob.sync('../Pages/**/*.js');
    return templateFiles.map(item => {

        return new HtmlWebpackPlugin({
            chunks: [item.replace('../Pages/', '').replace('.js', '')],
            template: `${item.replace('.js', '')}.cshtml`,
            filename: `${item.replace('../Pages/', '').replace('.js', '')}.cshtml`,
            inject: true
        });
    });
}


module.exports = {
    entry: glob.sync('../Pages/**/*.js').reduce((entries, entry) => Object.assign(entries, { [entry.replace('../Pages/', '').replace('.js', '')]: entry }), {}),
    // './app/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    module: {
        rules: [
            { test: /\.(js)$/, use: 'babel-loader' },
            {
                test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader']
            }
        ]
    },
    mode: 'development',


    plugins: [
            new CleanWebpackPlugin(),
            new MiniCssExtractPlugin()
        ]
        // We join our htmlPlugin array to the end
        // of our webpack plugins array.
        .concat(htmlPlugins)

};


//"scripts": {
//    "watch": "set NODE_ENV=development&&webpack --progress --colors --watch",
//        "deploy": "set NODE_ENV=production&&webpack -p"
//},
//<%= htmlWebpackPlugin.headTags %> broken <%= htmlWebpackPlugin.files.js.map(src => `<script type="text/javascript" src="${src}"></script>`).join("\r\n ") %>