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

module.exports = {
  context: path.resolve(__dirname, 'src', 'client'),
  mode: 'development',
  entry: {
    index: [
      'webpack-hot-middleware/client?path=http://localhost:7700/__webpack_hmr&timeout=20000&reload=true',
      './index.js',
    ]
  },
  output: {
    path: path.resolve(__dirname, 'public', 'static'),
    publicPath: '/static/',
    filename: "./bundle.js"
  },
  devtool: 'source-map',
  node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  },
  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=static/' // 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.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({'process.env': {'DEVELOPMENT': process.env.DEVELOPMENT}}),
    new webpack.LoaderOptionsPlugin({debug: true}),
    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.test.html', 'utf8');
      fs.writeFileSync('public/index.html', fileContent);
    })
  ]
};
