/* eslint-disable @typescript-eslint/no-var-requires */

const path = require('path');
class RTLCSSPlugin {
  constructor(options) {
    this.options = options || {};
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync('RTLCSSPlugin', (compilation, callback) => {
      // Explore each chunk (build output):
      compilation.chunks.forEach(chunk => {
        // Explore each asset filename generated by the chunk:
        chunk.files.forEach(filename => {
          // Get the asset source for each file generated by the chunk:
          const directory = path.dirname(filename),
            cssPath = this.options.path;
          if ((!cssPath || cssPath === directory) && path.extname(filename) === '.css') {
            const source = compilation.assets[filename].source();
            const rtlcss = require('rtlcss');
            const rtl = rtlcss.process(source);
            compilation.assets[`${directory}/${path.basename(filename, '.css')}.rtl.css`] = {
              source: function() {
                return rtl;
              },
              size: function() {
                return rtl.length;
              }
            };
          }
        });
      });
      callback();
    });
  }
}
module.exports = RTLCSSPlugin;
