const path = require('path');
const keysTransformer = require('ts-transformer-keys/transformer').default;
const SRC_DIR = path.join(__dirname, 'src');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = (env, argv) => {
  // 共通設定項目
  const BASE_CONFIG = {
    mode: 'mode' in argv ? argv['mode'] : 'development',
    output: {
      filename: '[name].js',
      path: path.join(__dirname, 'app'),
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: [
            {
              loader: 'ts-loader',
              options: {
                getCustomTransformers: p => ({
                  before: [keysTransformer(p)],
                }),
              },
            },
          ],
          exclude: [/node_modules/],
        },
        {
          resourceQuery: /raw/,
          type: 'asset/source',
        },
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
        }
      ],
    },
    resolve: {
      extensions: ['.tsx', '.ts', '.js'],
    },
  };

  return [
    // main
    Object.assign({}, BASE_CONFIG, {
      target: 'electron-main',
      entry: {
        main: path.join(SRC_DIR, 'main', 'main.ts'),
      },
      node: {
        __dirname: false,
        __filename: false,
      },
      externals: {
        serialport: "commonjs2 serialport"
      }
    }),
    // preload
    Object.assign({}, BASE_CONFIG, {
      target: 'electron-preload',
      entry: {
        preload: path.join(SRC_DIR, 'preload', 'preload.ts'),
      },
    }),
    // renderer
    Object.assign({}, BASE_CONFIG, {
      target: 'web',
      entry: {
        renderer: path.join(SRC_DIR, 'renderer', 'renderer.ts'),
      },
      plugins: [
        new CopyPlugin({
          patterns: [
            {
              from: path.join(__dirname, 'node_modules', 'blockly', 'media'),
              to: path.join(__dirname, 'app', 'blockly-media'),
            },
          ],
        }),
      ],
    }),
  ];
};
