"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RtlCssPlugin = void 0;

var _webpack = require("webpack");

var _OverwriteCssPathForRTL = _interopRequireDefault(require("./OverwriteCssPathForRTL"));

var _RTLSplitPlugin = require("../../../../postcss/custom_postcss_plugins/RTLSplitPlugin");

var _utils = require("../../utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// import HtmlWebpackPlugin from 'html-webpack-plugin';
// import rtlcss from 'rtlcss';
const pluginName = 'RtlCssPlugin';

class RtlCssPlugin {
  constructor(options = {}) {
    /**
     * @typedef {Object} Options
     * @property  {String} dirVarName
     * @property  {Boolean} sourcemap
     * @property  {Object} config
     */
    this.options = {
      // dirVarName: options.dirVarName || 'document.dir',
      sourcemap: options.sourcemap,
      config: options.config
    };
    this.templateLabel = options.templateLabel || '{{--dir}}';
    this.dirVarName = options.dirVarName || 'document.dir';
    this.rtlSplitOptions = {
      disableMinifySelector: options.disableMinifySelector
    };
  }

  apply(compiler) {
    const {
      RawSource
    } = compiler.webpack.sources;
    new _OverwriteCssPathForRTL.default({
      templateLabel: this.templateLabel,
      dirVarName: this.dirVarName
    }).apply(compiler); // const { filename, sourcemap, config } = this.options;
    // const { devtool } = compiler.options;
    // const postcssOptions = {
    //   map: (sourcemap === undefined && !!devtool) || !!sourcemap
    // };

    compiler.hooks.compilation.tap(pluginName, compilation => {
      // compilation.hooks.shouldGenerateChunkAssets.tap(pluginName, (...args) => {
      //   console.log('shouldGenerateChunkAssets', args);
      // });
      compilation.hooks.processAssets.tap({
        name: pluginName,
        stage: _webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY
      }, assets => {
        Object.keys(assets).filter(_utils.isCss).filter(_utils.isDirRelatedCss).forEach(chunkFilename => {
          const {
            source: asset
          } = compilation.getAsset(chunkFilename);
          const sourceStr = asset.source();
          const {
            ltr,
            rtl
          } = (0, _RTLSplitPlugin.separateRtlAndLtr)(sourceStr, this.rtlSplitOptions);
          const ltrFilename = chunkFilename.replace('[dir]', 'ltr');
          const rtlFilename = chunkFilename.replace('[dir]', 'rtl');
          compilation.renameAsset(chunkFilename, ltrFilename);
          compilation.updateAsset(ltrFilename, new RawSource(ltr));
          compilation.emitAsset(rtlFilename, new RawSource(rtl));
        });
      });
    });
  }

}

exports.RtlCssPlugin = RtlCssPlugin;