'use strict';

const fs = require('fs');
const process = require('process');
const path = require('path');
const webpackMerge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const HtmlWebpackExcludeAssetsPlugin = require('html-webpack-exclude-assets-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

const commonConfig = require('./webpack.common');

const staticHtmlFiles = fs
  .readdirSync(path.join(process.cwd(), 'static'))
  .filter(n => n.match(/.html$/))
  .map(n => {
    return new HtmlWebpackPlugin({
      template: path.join('static', n),
      filename: path.join(process.cwd(), 'dist/static', `${n}`),
    });
  });

const stylesheetRegex = /style-.+?\.css/;

module.exports = webpackMerge(commonConfig, {
  name: 'client',
  entry: {
    index: './src/client/index',
    chatEmbed: './src/client/chatEmbed',
    trafficSplitter: './src/client/trafficSplitter.ts',
  },
  module: {
    rules: [
      {
        test: /chatWorker\.js/,
        use: {
          loader: 'worker-loader',
          options: {
            name: 'bundle-chatWorker.js',
          },
        },
      },
    ],
  },
  target: 'web', // default
  output: {
    path: path.join(process.cwd(), '/dist/static/javascript'),
    filename: 'bundle-[name].js',
    publicPath: '/static/javascript/',
  },
  devtool: 'source-map',
  plugins: staticHtmlFiles.concat([
    new webpack.optimize.ModuleConcatenationPlugin(),
    new HtmlWebpackPlugin({
      chunks: ['index'],
      template: path.join(process.cwd(), '/src/client/index.html'),
      filename: path.join(process.cwd(), '/dist/server/index.html'),
      inject: 'head',
      excludeAssets: [stylesheetRegex],
    }),
    new HtmlWebpackPlugin({
      chunks: ['chatEmbed'],
      template: path.join(process.cwd(), '/src/client/ancillary.html'),
      filename: path.join(process.cwd(), '/dist/server/chatEmbed.html'),
      inject: 'head',
      excludeAssets: [stylesheetRegex],
    }),
    new HtmlWebpackExcludeAssetsPlugin(),
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: 'defer',
      preload: /\.js$/,
    }),
    new webpack.DefinePlugin({
      'process.env': {
        BROWSER: JSON.stringify(true),
      },
    }),
  ]),
});
