"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.setImports = setImports;
exports.createImports = createImports;

var codecClasses = _interopRequireWildcard(require("../../codec"));

var _create = require("../../codec/create");

var _types = require("../../codec/types");

var definitions = _interopRequireWildcard(require("../../interfaces/definitions"));

var primitiveClasses = _interopRequireWildcard(require("../../primitive"));

// Copyright 2017-2019 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// Maps the types as found to the source location. This is used to generate the
// imports in the output file, dep-duped and sorted
function setImports(imports, types) {
  const {
    codecTypes,
    localTypes,
    ignoredTypes,
    primitiveTypes,
    typesTypes
  } = imports;
  types.forEach(type => {
    if (ignoredTypes.includes(type)) {// do nothing
    } else if (['Codec', 'IExtrinsic', 'ITuple'].includes(type)) {
      typesTypes[type] = true;
    } else if (codecClasses[type]) {
      codecTypes[type] = true;
    } else if (primitiveClasses[type] || type === 'Metadata') {
      primitiveTypes[type] = true;
    } else if (type.includes('<') || type.includes('(') || type.includes('[')) {
      // If the type is a bit special (tuple, fixed u8, nested type...), then we
      // need to parse it with `getTypeDef`.
      const typeDef = (0, _create.getTypeDef)(type);
      setImports(imports, [_types.TypeDefInfo[typeDef.info]]); // TypeDef.sub is a `TypeDef | TypeDef[]`

      if (Array.isArray(typeDef.sub)) {
        typeDef.sub.forEach(subType => setImports(imports, [subType.type]));
      } else if (typeDef.sub) {
        // typeDef.sub is a TypeDef in this case
        setImports(imports, [typeDef.sub.type]);
      }
    } else {
      // find this module inside the exports from the rest
      const [moduleName] = Object.entries(definitions).find((_ref) => {
        let [, {
          types
        }] = _ref;
        return Object.keys(types).includes(type);
      }) || [null];

      if (moduleName) {
        localTypes[moduleName][type] = true;
      }
    }
  });
} // Create an Imports object, can be prefilled with `ignoredTypes`


function createImports() {
  let {
    types
  } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
    types: {}
  };
  const codecTypes = {};
  const localTypes = Object.keys(definitions).reduce((localTypes, moduleName) => {
    localTypes[moduleName] = {};
    return localTypes;
  }, {});
  const ignoredTypes = Object.keys(types);
  const primitiveTypes = {};
  const typesTypes = {};
  const imports = {
    codecTypes,
    localTypes,
    ignoredTypes,
    primitiveTypes,
    typesTypes
  };
  return imports;
}