'use strict';
const utils = require('./utils');
const config = require('./config');
const { merge } = require('webpack-merge');
const path = require('path');
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsPlugin = require('@soda/friendly-errors-webpack-plugin');
const portfinder = require('portfinder');

const PORT = '8080'

const devWebpackConfig = merge(baseWebpackConfig, {
  mode: 'development',
  devtool: 'eval-source-map',

  devServer: {
    client: {
      logging: 'warning',
      overlay: true,
      progress: true,
    },
    static: {
      directory: path.join(__dirname, '../static'),
    },
    historyApiFallback: {
      rewrites: [{ from: /.*/, to: path.posix.join(config.publicPath, 'index.html') }]
    },
    host: 'localhost',
    port: PORT,
    open: true,
    proxy: config.devServerProxy,
    watchFiles: {
      options: {
        usePolling: false,
      },
    }
  },
  plugins: [
    // new webpack.HotModuleReplacementPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
    }),
  ]
});

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = PORT;
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err);
    } else {
      // add port to devServer config
      devWebpackConfig.devServer.port = port;

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(
        new FriendlyErrorsPlugin({
          compilationSuccessInfo: {
            messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`]
          },
          onErrors: utils.createNotifierCallback()
        })
      );

      resolve(devWebpackConfig);
    }
  });
});
