// const nodeExternals = require('webpack-node-externals');
const merge = require('webpack-merge');
const WebpackBar = require('webpackbar');

// local
const HTMLWebpackPlugin = require('html-webpack-plugin');
const parts = require('./parts');
const commonConfig = require('./common');
const paths = require('.././paths');
// Forces webpack-dev-server program to write bundle files to the file system.

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

  return merge([
    parts.clean(paths.defaultBuild, paths.baseDir),
    {
      name: 'electron',
      entry: {
        main: [paths.main],
      },
      target: 'electron-main',
      // node: { __dirname: false },
      // in prod we need the packages
      node: {
        // tell webpack that we actually want a working __dirname value
        // (ref: https://webpack.js.org/configuration/node/#node-__dirname)
        __dirname: false,
        __filename: false,
      },
      output: {
        path: paths.defaultBuild,
        filename: 'main.js',
        publicPath: './',
      },
    },
    // investigate why adding prod true destory ssr in prod
    parts.loadJavaScript(),
    // need css loader to not fail building
    parts.loadCSS(),
    parts.setVariables({
      __ELECTRON__: true,
      __TEST__: false,
      __BROWSER__: false,
      __SSR__: false,
      __PLATFORM__: config.platform || 'default',
      __ENV__: config.environment || 'default',
      __PROVIDER__: config.provider || 'default',
    }),
    {
      plugins: [
        new HTMLWebpackPlugin({
          template: paths.inAppSrc('index.html'),
        }),
        new WebpackBar({
          name: 'Electron',
          color: 'orange',
        }),
      ],
    },
    // 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(commonConfig, config);
};
