const HTMLWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const WebpackBar = require('webpackbar');
const Dotenv = require('dotenv-webpack');

const merge = require('webpack-merge');
const webpack = require('webpack');
// local
const parts = require('./parts');
const commonConfig = require('./common');
const paths = require('../paths');

const createConfig = config => {
  const isProduction = config.mode === 'production';

  return merge([
    // clean in prod
    parts.clean(paths.defaultBuild, paths.baseDir),
    {
      name: 'app',
      // Entries configuration
      entry: {
        main: [paths.main],
      },
      // Source mapping or not
      devtool: config.prod ? 'none' : 'eval-source-map',
      output: {
        path: paths.defaultBuild,
        filename: 'main.js',
        publicPath: './',
      },
    },
    parts.loadJavaScript({
      prod: config.prod,
    }),
    parts.loadCSS({
      prod: config.prod,
    }),
    parts.setVariables({
      __BROWSER__: true,
      __SSR__: false,
      __TEST__: false,
      __PLATFORM__: config.platform || 'default',
      __PROVIDER__: config.provider || 'default',
      __ENV__: config.environment || 'default',
    }),
    {
      plugins: [
        new HTMLWebpackPlugin({
          template: paths.inAppSrc('index.html'),
        }),
        new WebpackBar(),
      ],
    },
    // Prod plugins
    isProduction && parts.imageOptimization(),
    parts.optimize(),
  ]);
};

module.exports = (env, params) => {
  const config = createConfig({
    mode: params.locale ? 'development' : 'production',
    port: params.port,
    analyze: params.analyze,
    platform: params.platform,
    provider: params.provider,
    environment: params.environment,
  });

  // mode : Possible values for mode are: none, development or production(default).
  return merge(config, commonConfig);
};
