"use strict";

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

var _htmlWebpackPlugin = _interopRequireDefault(require("html-webpack-plugin"));

var _JavascriptModulesPlugin = _interopRequireDefault(require("webpack/lib/javascript/JavascriptModulesPlugin"));

var _replaceCssDirTemplate = require("./replaceCssDirTemplate");

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

// const HtmlWebpackPlugin = require('html-webpack-plugin');
// import { JavascriptModulesPlugin } from 'webpack';
const pluginName = 'OverwriteCssPathForRTL';

class OverwriteCssPathForRTL {
  constructor(options = {
    dirVarName: 'document.dir'
  }) {
    this.dirVarName = options.dirVarName || 'document.dir';
    this.templateLabel = options.templateLabel || '{{--dir}}';
  }

  overwriteCssPathinHTML(compilation) {
    // NOTE: need to reconsider It is not working as expected
    _htmlWebpackPlugin.default.getHooks(compilation).beforeAssetTagGeneration.tapAsync(pluginName, (data, cb) => {
      const {
        assets
      } = data;
      cb(null, { ...data,
        assets: { ...assets,
          css: assets.css && (0, _replaceCssDirTemplate.replaceCssDirTemplateMapper)(assets.css, this.templateLabel)
        }
      });
    });
  }

  overwriteCssPathinRequireEnsure(compilation, compiler) {
    const {
      RawSource
    } = compiler.webpack.sources;

    _JavascriptModulesPlugin.default.getCompilationHooks(compilation).renderMain.tap(pluginName, source => {
      const templateText = `"+(${this.dirVarName} === "rtl" ? ".rtl": ".ltr")+"`;
      const replacedStr = source.source().replace(/\[dir\]/g, templateText);
      return new RawSource(replacedStr);
    });
  }

  apply(compiler) {
    compiler.hooks.thisCompilation.tap(pluginName, compilation => {
      this.overwriteCssPathinHTML(compilation);
      this.overwriteCssPathinRequireEnsure(compilation, compiler);
    });
  }

}

exports.default = OverwriteCssPathForRTL;