"use strict";

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

var _path = _interopRequireDefault(require("path"));

var _webpackSources = require("webpack-sources");

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

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

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

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

const isCss = filename => _path.default.extname(filename) === '.css'; // this  plugin code copy from https://github.com/nicolashemonic/rtl-css-transform-webpack-plugin


class RtlCssPlugin {
  constructor(options = {}) {
    /**
     * @typedef {Object} Options
     * @property  {String} filename [not used]
     * @property  {String} dirVarName
     * @property  {Boolean} sourcemap
     * @property  {Object} config
     */
    this.options = {
      filename: options.filename || '[name].rtl.css',
      // dirVarName: options.dirVarName || 'document.dir',
      sourcemap: options.sourcemap,
      config: options.config
    };
    this.templateLabel = options.templateLabel || '{{--dir}}';
    this.dirVarName = options.dirVarName || 'document.dir';
    this.rtlSplitOptions = {
      disableMiniFiySelector: options.disableMiniFiySelector
    };
  }

  apply(compiler) {
    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.optimizeChunkAssets.tapAsync(pluginName, (chunks, callback) => {
        chunks.forEach(chunk => {
          chunk.files.filter(isCss).forEach(chunkFilename => {
            const asset = compilation.assets[chunkFilename];
            const sourceStr = asset.source();
            const {
              ltr,
              rtl
            } = (0, _RTLSplitPlugin.separateRtlAndLtr)(sourceStr, this.rtlSplitOptions); // const result = rtlcss
            //   .configure(config)
            //   .process(asset.source(), postcssOptions);

            const assetFilename = chunkFilename.replace('.ltr.', '.rtl.');
            compilation.assets[chunkFilename] = new _webpackSources.RawSource(ltr);
            compilation.assets[assetFilename] = new _webpackSources.RawSource(rtl);
          });
        });
        callback();
      });
    });
  }

}

exports.RtlCssPlugin = RtlCssPlugin;