"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.
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("@polkadot/util");
const codec_1 = require("../../../types/codec");
/** @internal */
function toV1Calls(registry, { module: { call: { functions } } }) {
    return functions.length
        ? new codec_1.Option(registry, codec_1.Vec.with('FunctionMetadataV1'), functions)
        : new codec_1.Option(registry, codec_1.Vec.with('FunctionMetadataV1'));
}
/** @internal */
function toV1Events(registry, metadataV0, prefix) {
    const events = metadataV0.outerEvent.events.find((event) => event[0].eq(prefix));
    return events
        ? new codec_1.Option(registry, codec_1.Vec.with('EventMetadataV1'), events[1])
        : new codec_1.Option(registry, codec_1.Vec.with('EventMetadataV1'));
}
/** @internal */
function toV1Storage(registry, { storage }) {
    return storage.isSome
        ? new codec_1.Option(registry, 'Vec<StorageFunctionMetadataV1>', storage.unwrap().functions)
        : new codec_1.Option(registry, 'Vec<StorageFunctionMetadataV1>');
}
/** @internal */
function toV1(registry, metadataV0) {
    return codec_1.createType(registry, 'MetadataV1', {
        modules: metadataV0.modules.map((mod) => {
            // The prefix of this module (capitalized)
            const prefix = mod.storage.isSome
                ? mod.storage.unwrap().prefix.toString()
                : util_1.stringUpperFirst(mod.prefix.toString()); // If this module doesn't have storage, we just assume the prefix is the name capitalized
            return codec_1.createType(registry, 'ModuleMetadataV1', {
                name: mod.prefix,
                prefix,
                storage: toV1Storage(registry, mod),
                calls: toV1Calls(registry, mod),
                events: toV1Events(registry, metadataV0, mod.prefix)
            });
        })
    });
}
exports.default = toV1;
