"use strict";

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

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

var _icssUtils = require("icss-utils");

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

const pluginName = 'postcss-icss-parser';

var _default = _postcss.default.plugin(pluginName, () => function process(css, result) {
  const importReplacements = Object.create(null);
  const {
    icssImports,
    icssExports
  } = (0, _icssUtils.extractICSS)(css);
  Object.keys(icssImports).forEach((url, importIndex) => {
    const tokens = Object.keys(icssImports[url]);

    if (tokens.length === 0) {
      return;
    }

    const importName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}___`;
    result.messages.push({
      pluginName,
      type: 'import',
      value: {
        type: 'icss-import',
        name: importName,
        url
      }
    });
    tokens.forEach((token, replacementIndex) => {
      const name = `___CSS_LOADER_ICSS_IMPORT_${importIndex}_REPLACEMENT_${replacementIndex}___`;
      const localName = icssImports[url][token];
      importReplacements[token] = name;
      result.messages.push({
        pluginName,
        type: 'replacer',
        value: {
          type: 'icss-import',
          name,
          importName,
          localName
        }
      });
    });
  });

  if (Object.keys(importReplacements).length > 0) {
    (0, _icssUtils.replaceSymbols)(css, importReplacements);
  }

  Object.keys(icssExports).forEach(name => {
    const value = (0, _icssUtils.replaceValueSymbols)(icssExports[name], importReplacements);
    result.messages.push({
      pluginName,
      type: 'export',
      value: {
        name,
        value
      }
    });
  });
});

exports.default = _default;