const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ElectronConnectWebpackPlugin = require('electron-connect-webpack-plugin');
const nodeExternals = require('webpack-node-externals');

const { hasProcessFlag, root } = require('./helpers.js');
const { getReplacements } = require('./app-info');

const replacements = getReplacements();

const EVENT = process.env.npm_lifecycle_event || '';
const PROD = EVENT.includes('prod');


module.exports = function () {
  const tsConfigBase = './src/tsconfig.electron.json';

  const atlConfig = {
    configFileName: tsConfigBase
  };

  let config = Object.assign({});
  config.target = 'electron-main';
  config.mode = PROD ? 'production' : 'development';
  config.devtool = PROD ? false : 'cheap-module-source-map';
  config.externals = [nodeExternals()];
  config.entry = {
    'index': root('src', 'electron', 'main.ts')
  };
  config.output = {
    path: PROD ? root('build', 'dist') : root('build', 'dev'),
    filename: '[name].js',
    sourceMapFilename: '[file].map',
  };
  config.resolve = {
    extensions: ['.ts', '.tsx', '.mjs', '.js'],
    modules: [
      root(),
      'node_modules'
    ],
  }
  config.module = {
    rules: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader?' + JSON.stringify(atlConfig)
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      }
    ]
  };
  config.node = {
    __dirname: false,
    __filename: false
  };
  config.plugins = [
    PROD ? new webpack.NoEmitOnErrorsPlugin() : null,
    PROD ? new CopyWebpackPlugin(
      [
        'config/package.json'
      ]
    ) : null,
    new webpack.DefinePlugin(
      Object.assign({}, replacements, {
        __PROCESS_KIND__: JSON.stringify('main'),
      })
    ),
    PROD ? null : new ElectronConnectWebpackPlugin({
      path: root('build', 'dev'),
      stopOnClose: true,
      logLevel: 0
    })
  ].filter(plugin => plugin !== null);

  return config;

}();