const path = require('path');
const webpack = require('webpack');
const AssetsWebpackPlugin = require('assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const merge = require('webpack-merge').merge;
const wpConfig = require('./webpack.config.json');

let env = process.env.NODE_ENV || 'development';
const devMode = env === 'development';
const outputPath = path.join(__dirname, wpConfig.buildDir);
const publicPath = '/' + wpConfig.buildDir + '/';

const baseConfig = {
	entry: wpConfig.entry,
	mode: devMode ? 'development' : 'production',
	output: {
		path: outputPath,
		publicPath: publicPath
	},
	module: {
		rules: [
			{
				test: /\.m?js$/,
				exclude: /(node_modules|bower_components)/,
				use: {
					loader: 'babel-loader',
						options: {
						presets: ['@babel/preset-env']
					}
				}
			}, {
				test: /tinymce\/.*\/skin\.css$/i,
				use: [MiniCssExtractPlugin.loader, 'css-loader']
			}, {
				test: /tinymce\/.*\/content\.css$/i,
				loader: 'css-loader',
				options: {esModule: false}
			}, {
				test: /\.css$/,
				use: ['style-loader', 'css-loader'],
				exclude: [/node_modules/]
			}, {
				test: /\.yml$/,
				use: ['json-loader', 'yaml-loader']
			}, {
				test: /\.xml$/,
				use: 'raw-loader'
			}, {
				test: /\.ttf$/,
				type: 'asset/resource'
			}, {
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					{
						loader: 'sass-loader',
						options: {
							sourceMap: true
						}
					}
				]
			}
		]
	},
	resolve: {
		modules: [
			__dirname +'/js',
			__dirname,
			__dirname +'/forms',
			'node_modules',
			'/usr/lib/node_modules'
		]
	},
	node: {
		__dirname: true
	},
	plugins: [
		new AssetsWebpackPlugin({
			path: outputPath
		}),
		new webpack.DefinePlugin({
			_DEV_MODE: devMode,
			_DEV_SERVER_PORT: wpConfig.devServerPort,
			_PUBLIC_PATH: JSON.stringify(publicPath)
		}),
		new MiniCssExtractPlugin()
	],
	optimization: {
		runtimeChunk: true,
		splitChunks: {
			chunks: 'all',
		}
	},
	watchOptions: {
		ignored: /node_modules/
	}
};

const prodConfig = {
	output: {
		filename: '[name].[chunkhash].js',
		chunkFilename: 'chunk.[id].[chunkhash].js'
	},
	optimization: {
		moduleIds: 'deterministic'
	},
	devtool: 'source-map'
};

const devConfig = {
	output: {
		filename: '[name].js',
		chunkFilename: 'chunk.[id].js'
	},
	optimization: {
		moduleIds: 'named'
	},
	devtool: 'eval',
	devServer: {
		host: '0.0.0.0',
		static: __dirname,
		port: wpConfig.devServerPort,
		headers: {'Access-Control-Allow-Origin': '*'},
		//stats: { chunks: false },
		proxy: {
			'/api': 'http://localhost:3000',
			'/': {
				target: 'http://localhost:3001',
				bypass: (req) => req.path !== '/' ? req.path : null
			}
		}
	}
};

const mrgConfig = devMode ? devConfig : prodConfig;
module.exports = merge(baseConfig, mrgConfig);
