"use strict";

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

var _postcss = _interopRequireDefault(require("postcss"));

var _fs = _interopRequireDefault(require("fs"));

var _selectorWeightPrefixAdder = require("./selectorWeightPrefixAdder");

var _checkIsPatternsMatchFilename = require("../../loaderConfigs/checkIsPatternsMatchFilename");

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

class SelectorWeightPlugin {
  constructor(options = {}) {
    this.options = {
      selectorWeightConfig: options.configFile,
      defaultSelector: options.defaultSelector,
      customFileDetails: options.customFileDetails,
      excludeStrings: options.excludeStrings,
      patterns: options.patterns
    };
  }

  apply(compiler) {
    const {
      defaultSelector,
      customFileDetails,
      excludeStrings,
      patterns
    } = this.options;

    const rawdata = _fs.default.readFileSync(customFileDetails);

    const data = JSON.parse(rawdata);
    compiler.hooks.compilation.tap('selector-weight-rewrite', compilation => {
      compilation.hooks.optimizeModules.tap('selector-weight-rewrite', modules => {
        const mods = Array.from(modules).filter(x => x.type.includes('css'));
        mods.forEach(module => {
          const filename = module.issuer.resource;

          if (!(0, _checkIsPatternsMatchFilename.checkIsPatternsMatchFilename)(patterns, filename)) {
            return;
          }
          /*
           
          filename : Deskapp.module.css ?
            data : 
          {
              "DeskApp.module.css": {"defaultSelector" : ".desk_app_ui "}
          }
              selectorWeightConfig : 
            defaultSelector : .zoho_desk_ui
          
          case filename = 'DeskApp.module.css' ? 
          data[filename].defaultSelector = '.desk_app_ui' 
            case filename is different ?
          defaultSelector = '.zoho_desk_ui'
            */


          const rootOriginal = _postcss.default.parse(module.content); // eslint-disable-next-line no-param-reassign


          module.content = (0, _selectorWeightPrefixAdder.selectorWeightPrefixAdder)(rootOriginal, data[filename] ? data[filename].defaultSelector : defaultSelector, excludeStrings).toString();
        });
      });
    });
  }

}

var _default = SelectorWeightPlugin;
exports.default = _default;