const merge = require('webpack-merge');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const chokidar = require('chokidar');
const { execSync } = require('child_process');
const { resolve } = require('path');

const dirs = require('./dirs');

const common = require('./webpack.common.js');

// 监听国际化文件并编译
chokidar
    .watch(resolve(__dirname, '../../main/resources/com/fr/plugin/db/json/locale/json_zh_CN.properties'), { ignored: /(^|[/\\])\../ })
    .on('all', (event, path) => {
        try {
            execSync('npm run i18n');
        } catch (e) {
            console.error(e);
        }
    });

module.exports = merge(common, {
    devtool: 'eval-source-map',
    entry: {
        i18n: [
            './src/i18n.ts',
        ],
        show: [
            './src/index.show.ts',
        ],
        edit: [
            './src/index.edit.ts',
        ],
    },
    externals: {
        CodeMirror: 'CodeMirror',
    },
    output: {
        path: dirs.DEST,
        filename: '[name].[contenthash].js',
    },
    devServer: {
        contentBase: path.join(__dirname, '..'),
        port: 10002,
        liveReload: true,
    },
    plugins: [
        new MiniCssExtractPlugin({
            path: dirs.DEST,
            filename: 'show.dev.[contenthash].css',
        }),
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '../index.html'),
            chunks: ['polyfill', 'i18n', 'edit'],
            chunksSortMode: 'manual',
            title: 'Redis插件编辑界面',
        }),
        new HtmlWebpackPlugin({
            filename: 'show/index.html',
            template: path.resolve(__dirname, '../index.html'),
            chunks: ['polyfill', 'i18n', 'show'],
            chunksSortMode: 'manual',
            title: 'Redis插件预览界面',
        }),
        new ForkTsCheckerWebpackPlugin({
            watch: ['./src'],
        }),
        new OptimizeCssAssetsPlugin({
            assetNameRegExp: /\.css$/g,
            cssProcessor: require('cssnano'),
            cssProcessorPluginOptions: {
                preset: ['default', {
                    discardComments: {
                        removeAll: true,
                    },
                    normalizeUnicode: false,
                }],
            },
            canPrint: true,
        }),
    ],
});