'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var types = require('../types-4940caff.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);

/**
 * 替换引用
 *
 * @param {string} content 输入内容
 * @param {Array<IParsedConfigItem>} parsedConfigList 替换配置
 * @param {string} keyword 提前返回关键词
 * @returns {string} 处理后的内容
 *
 * @example
 * ```ts
 * replaceDependencies('', [], '@tx/pmd-vue')
 * ```
 */
function replaceDependencies(content, parsedConfigList, keyword) {
  var parser = require('@babel/parser');
  var traverse = require('@babel/traverse')["default"];
  var generator = require('@babel/generator');
  var replaced = false;
  var ast = parser.parse(content, {
    // 不加这个配置，报错：SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"'
    sourceType: 'module',
    plugins: ['typescript']
  });
  traverse(ast, {
    ImportDeclaration: function ImportDeclaration(path) {
      var sourceValue = path.node.source.value;
      var importedList = path.node.specifiers.map(function (item) {
        var _a;
        var type = item.type;
        return {
          type: type,
          local: item.local.name,
          imported: ((_a = item.imported) === null || _a === void 0 ? void 0 : _a.name) || ''
        };
      });
      if (sourceValue.includes(keyword)) return;
      var target = getTarget(sourceValue, importedList, parsedConfigList);
      target.forEach(function (item) {
        path.insertAfter(item);
      });
      if (target.length) {
        path.remove();
        replaced = true;
      }
    }
  });
  var output = generator["default"](ast, {});
  if (replaced) {
    return output.code;
  }
  return content;
}
function localFlatten(list) {
  return list.reduce(function (acc, current) {
    var target = current.target;
    if (acc[target]) {
      acc[target].push(current);
    } else {
      acc[target] = [current];
    }
    return acc;
  }, {});
}
function getTarget(originSource, originImportedList, parsedConfigList) {
  if (!originImportedList.length) {
    var foundItem = parsedConfigList.find(function (item) {
      return item.source === originSource;
    });
    if (!(foundItem === null || foundItem === void 0 ? void 0 : foundItem.target)) {
      return [];
    }
    return [genNewImport(foundItem === null || foundItem === void 0 ? void 0 : foundItem.target, [])];
  }
  var parsedImportList = originImportedList.map(function (curOrigin) {
    var current = parsedConfigList.find(function (item) {
      var source = item.source,
        sourceType = item.sourceType,
        sourceName = item.sourceName;
      if (originSource !== source || curOrigin.type !== sourceType) {
        return false;
      }
      if (sourceType === types.IImportType.ImportSpecifier) {
        return curOrigin.imported === sourceName;
      }
      // ImportDefaultSpecifier 和 ImportNamespaceSpecifier 直接返回 true
      return true;
    });
    if (!current) {
      return Object.assign(Object.assign({}, curOrigin), {
        _type: 'OLD',
        target: originSource,
        targetName: curOrigin.imported,
        targetType: curOrigin.type
      });
    }
    return Object.assign(Object.assign(Object.assign({}, current), curOrigin), {
      _type: 'NEW'
    });
  });
  var newImportList = parsedImportList.filter(function (item) {
    return item._type === 'NEW';
  });
  var oldImportList = parsedImportList.filter(function (item) {
    return item._type === 'OLD';
  });
  var obj = localFlatten(newImportList);
  var oldObj = localFlatten(oldImportList);
  // newImportList.reduce((acc: Record<string, Array<{
  //   type: IImportType;
  //   local: string;
  //   imported: string;
  //   source: string;
  //   target: string;
  //   sourceName: string;
  //   sourceType: IImportType;
  //   targetName: string;
  //   targetType: IImportType;
  // }>>, current) => {
  //   const { target } = current!;
  //   if (acc[target]) {
  //     acc[target].push(current!);
  //   } else {
  //     acc[target] = [current!];
  //   }
  //   return acc;
  // }, {});
  var nodeList = Object.keys(obj).map(function (source) {
    var node = genNewImport(source, obj[source]);
    return node;
  });
  var oldNodeList = Object.keys(oldObj).map(function (source) {
    var node = genNewImport(source, oldObj[source]);
    return node;
  });
  if (nodeList.length) {
    return [].concat(_toConsumableArray__default["default"](nodeList), [oldNodeList]);
  }
  return [];
}
function genNewImport(source, importedList) {
  var t = require('@babel/types');
  var list = importedList.map(function (current) {
    var local = current.local,
      targetType = current.targetType,
      targetName = current.targetName;
    if (targetType === types.IImportType.ImportSpecifier) {
      return t.ImportSpecifier(t.identifier(local), t.identifier(targetName));
    }
    if (targetType === types.IImportType.ImportDefaultSpecifier) {
      return t.ImportDefaultSpecifier(t.identifier(local));
    }
    if (targetType === types.IImportType.importNamespaceSpecifier) {
      return t.ImportNamespaceSpecifier(t.identifier(local));
    }
  });
  return t.ImportDeclaration(list, t.StringLiteral(source));
}

exports.replaceDependencies = replaceDependencies;
