"use strict";

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

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

var _util = require("@polkadot/util");

var _MagicNumber = require("./MagicNumber");

var _MetadataVersioned = _interopRequireDefault(require("./MetadataVersioned"));

// 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.

/**
 * @name Metadata
 * @description
 * The versioned runtime metadata as a decoded structure
 */
class Metadata extends _MetadataVersioned.default {
  constructor(value) {
    super(Metadata.decodeMetadata(value));
  } // first we try and parse using the versioned structure, if this does fail,
  // we adjust with the magic number and a manual version and re-try. As soon as
  // we remove support for V0, we will just do a new here


  static decodeMetadata() {
    let _value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Uint8Array();

    const value = (0, _util.isHex)(_value) ? (0, _util.hexToU8a)(_value) : _value;

    try {
      return new _MetadataVersioned.default(value);
    } catch (error) {
      if (error.message.indexOf('MagicNumber mismatch') === -1) {
        throw error;
      }
    }

    return new _MetadataVersioned.default((0, _util.u8aConcat)(_MagicNumber.MAGIC_NUMBER.toU8a(), // manually add the magic number
    Uint8Array.from([0]), // add the version for the original
    value // the actual data as retrieved
    ));
  }

}

exports.default = Metadata;