import * as path from 'path';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import * as CopyWebpackPlugin from 'copy-webpack-plugin';
import * as webpack from 'webpack';
import * as nodeExternals from 'webpack-node-externals';
import { getEnviroments } from './enviroment';

const enviroments = getEnviroments();

export const externals = [nodeExternals()];
// if (enviroments.__DEV__) {
//   externals.push('devtron');
// }

const outputDir = 'dist/main';

const mainConfig: webpack.Configuration = {
  entry: { main: path.resolve(__dirname, '..', 'main/src/index') },
  target: 'electron-main',
  mode: enviroments.__DEV__ ? 'development' : 'production',
  devtool: 'source-map',
  optimization: {
    noEmitOnErrors: true
  },
  externals,
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, '..', outputDir)
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        include: [
          path.resolve(__dirname, '..', 'main/src'),
          path.resolve(__dirname, '..', 'projects')
        ],
        use: [
          {
            loader: 'awesome-typescript-loader',
            options: {
              useCache: true,
              configFileName: path.resolve(
                __dirname,
                '..',
                'main/tsconfig.main.json'
              )
            }
          }
        ],
        exclude: /node_modules/
      },
      {
        test: /\.node$/,
        loader: 'awesome-node-loader',
        options: {
          name: '[name].[ext]'
        }
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin({ verbose: false }),
    // This saves us a bunch of bytes by pruning locales (which we don't use)
    // from moment.
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin(
      Object.assign({}, enviroments, {
        __PROCESS_KIND__: JSON.stringify('main')
      })
    ),
    new CopyWebpackPlugin([
      {
        from: 'main/resources/**/*',
        to: path.resolve(__dirname, '..', 'dist')
      }
    ])
  ],
  resolve: {
    extensions: ['.js', '.ts'],
    alias: {
      '@ucap-webmessenger/native': path.resolve(
        __dirname,
        '..',
        'projects/ucap-webmessenger-native/src/public-api'
      ),
      '@ucap-webmessenger/native-electron': path.resolve(
        __dirname,
        '..',
        'projects/ucap-webmessenger-native-electron/src/public-api'
      )
    },
    modules: [path.resolve(__dirname, '..', 'node_modules/')]
  },
  node: {
    __dirname: false,
    __filename: false
  }
};

export default [mainConfig];