"use strict";
const path = require('path');
const fs = require('fs-extra-promise');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackOnBuildPlugin = require('on-build-webpack');
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({size: 8});

module.exports = {
  context: path.resolve(__dirname, 'src', 'client'),
  mode: 'production',
  entry: {
    index: ['./index.js']
  },
  output: {
    path: path.resolve(__dirname, 'public', 'dist'),
    publicPath: '/dist/',
    filename: "./bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.woff2?(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url-loader?limit=10000&mimetype=application/font-woff"
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url-loader?limit=10000&mimetype=application/octet-stream"
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: "file-loader"
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url-loader?limit=10000&mimetype=image/svg+xml"
      }, {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        use: 'happypack/loader?id=jsx',
      }, {
        test: /\.css?$/,
        use: 'happypack/loader?id=styles'
      }, {
        test: /\.scss?$/,
        use: 'happypack/loader?id=styles'
      }, {
        test: /\.sass?$/,
        use: 'happypack/loader?id=styles'
      }, {
        test: /\.(jpg|png)$/,
        loaders: [
          'url-loader?limit=10000&publicPath=dist/' // Any png-image or woff-font below or equal to 10K will be converted to inline base64 instead
        ]
      }, {
        test: /\.md$/,
        loaders: 'raw-loader'
      }
    ]
  },
  plugins: [
    new webpack.ProgressPlugin(),
    new CopyWebpackPlugin([
      {from: './../../assets', to: './../../public/assets'}
    ]),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new MiniCssExtractPlugin(),
    new HappyPack({
      id: 'jsx',
      threadPool: happyThreadPool,
      loaders: ['babel-loader']
    }),
    new HappyPack({
      id: 'styles',
      threadPool: happyThreadPool,
      loaders: ['style-loader', 'css-loader', 'sass-loader']
    }),
    new WebpackOnBuildPlugin(function (stats) {
      let fileContent = fs.readFileSync('public/index.prod.html', 'utf8');
      fs.writeFileSync('public/index.html', fileContent);
    })
  ]
};
