"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

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

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

var _flattenUniq = _interopRequireDefault(require("./flattenUniq"));

var _codec = require("../../codec");

// 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.
function extractTypes(types) {
  return types.map(type => {
    const decoded = (0, _create.getTypeDef)(type);

    switch (decoded.info) {
      case _types.TypeDefInfo.Plain:
        return decoded.type;

      case _types.TypeDefInfo.Compact:
      case _types.TypeDefInfo.Option:
      case _types.TypeDefInfo.Vec:
        return extractTypes([decoded.sub.type]);

      case _types.TypeDefInfo.VecFixed:
        return extractTypes([decoded.ext.type]);

      case _types.TypeDefInfo.Result:
      case _types.TypeDefInfo.Tuple:
        return extractTypes(decoded.sub.map(sub => sub.type));

      default:
        throw new Error("Unhandled: Unable to create and validate type from ".concat(type));
    }
  });
}

function validateTypes(types, throwError) {
  const typeRegistry = (0, _codec.getTypeRegistry)();
  const missing = (0, _flattenUniq.default)(extractTypes(types)).filter(type => !typeRegistry.hasType(type));

  if (missing.length !== 0) {
    const message = "Unknown types found, no types for ".concat(missing);

    if (throwError) {
      throw new Error(message);
    } else {
      console.warn(message);
    }
  }
}