const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const { styles } = require('@ckeditor/ckeditor5-dev-utils');
const TerserPlugin = require('terser-webpack-plugin');

function getDirectories(srcpath) {
  return fs
      .readdirSync(srcpath)
      .filter((item) => fs.statSync(path.join(srcpath, item)).isDirectory());
}

module.exports = [];
// Loop through every subdirectory in src, each a different plugin, and build
// each one in ./build.
getDirectories('./ckeditor5_plugins').forEach((dir) => {
  const bc = {
    mode: 'production',
    optimization: {
      minimize: true,
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            format: { comments: false },
          },
          test: /\.js(\?.*)?$/i,
          extractComments: false,
        }),
      ],
      moduleIds: 'named',
    },
    entry: path.resolve(__dirname, 'ckeditor5_plugins', dir, 'src/index.js'),
    output: {
      path: path.resolve(__dirname, './build'),
      filename: `${dir}.js`,
      library: ['CKEditor5', dir],
      libraryTarget: 'umd',
      libraryExport: 'default',
    },
    externals: [
      function({ context, request }, callback) {
        if (request === 'ckeditor5') {
          return callback(null, `root (function() {
            const CKEditor5 = window.CKEditor5;
            const exports = {};
            Object.keys(CKEditor5).forEach(moduleName => {
              const module = CKEditor5[moduleName];
              if (module && typeof module === 'object' && !Array.isArray(module)) {
                Object.assign(exports, module);
              }
            });
            
            return exports;
          })()`);
        }
        callback();
      }
    ],
    module: {
      rules: [
        {
          test: /theme[/\\]icons[/\\][^/\\]+\.svg$/,
          use: ['raw-loader'],
        },
        {
          test: /theme[/\\].+\.css$/,
          use: [
            {
              loader: 'style-loader',
              options: {
                injectType: 'singletonStyleTag',
                attributes: { 'data-cke': true },
              },
            },
            {
              loader: 'postcss-loader',
              options: styles.getPostCssConfig({
                themeImporter: {
                  themePath: require.resolve('@ckeditor/ckeditor5-theme-lark'),
                },
                minify: true,
              }),
            },
          ],
        },
      ],
    },
  };

  module.exports.push(bc);
});
