"use strict";
// Copyright 2017-2020 @polkadot/metadata authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("@polkadot/util");
const MagicNumber_1 = require("./MagicNumber");
const MetadataVersioned_1 = __importDefault(require("./MetadataVersioned"));
/**
 * @name Metadata
 * @description
 * The versioned runtime metadata as a decoded structure
 */
class Metadata extends MetadataVersioned_1.default {
    constructor(registry, value) {
        super(registry, Metadata.decodeMetadata(registry, 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(registry, _value = new Uint8Array()) {
        const value = util_1.isHex(_value)
            ? util_1.hexToU8a(_value)
            : _value;
        try {
            return new MetadataVersioned_1.default(registry, value);
        }
        catch (error) {
            if (error.message.indexOf('MagicNumber mismatch') === -1) {
                throw error;
            }
        }
        return new MetadataVersioned_1.default(registry, util_1.u8aConcat(util_1.bnToU8a(MagicNumber_1.MAGIC_NUMBER), // manually add the magic number
        Uint8Array.from([0]), // add the version for the original
        value // the actual data as retrieved
        ));
    }
}
exports.default = Metadata;
