"use strict";

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

/* eslint-disable no-param-reassign */
var _default = (opts = {}) => {
  // eslint-disable-next-line no-use-before-define
  validator(opts);
  const {
    before,
    after
  } = opts;
  return {
    postcssPlugin: 'postcss-selector-replace',

    Once(root) {
      root.walkRules(rule => {
        before.forEach((beforeOpt, idx) => {
          const afterOpt = after[idx];

          if (typeof beforeOpt === 'string') {
            rule.selector = rule.selector.split(beforeOpt).join(afterOpt);
          } else {
            rule.selector = rule.selector.replace(beforeOpt, afterOpt);
          }
        });
      });
    }

  };
};

exports.default = _default;

function validator(opts) {
  if (!opts || typeof opts !== 'object') {
    throw new Error('Always requires argment');
  }

  const {
    before,
    after
  } = opts;

  if (!before || !after) {
    throw new Error('Be sure to have "before" and "after" object names');
  }

  if (!Array.isArray(before) || !Array.isArray(after)) {
    throw new Error('Objects "before" and "after" must be of type Array');
  }

  if (before.length !== after.length) {
    throw new Error('Length of before and after options must be the same');
  }

  if (before.length === 0) {
    throw new Error('Array length is 1 or more');
  }

  before.forEach((beforeOpt, idx) => {
    const afterOpt = after[idx];

    switch (true) {
      case typeof beforeOpt === 'string':
        {
          if (!typeof afterOpt === 'string') {
            throw new Error(`The after option ${afterOpt} must be a string. If you want to apply the replace callback function, then use a RegExp for the before option`);
          }

          break;
        }

      case beforeOpt instanceof RegExp:
        {
          if (!typeof afterOpt === 'string' && !typeof afterOpt === 'function') {
            throw new Error(`The after option ${afterOpt} must be either a string, or a function`);
          }

          break;
        }

      default:
        throw new Error(`The before option ${beforeOpt} must be either a string, or a RegExp`);
    }
  });
}