"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 codec_1 = require("../../../types/codec");
/** @internal */
function toV4StorageFunction(registry, storageFn) {
    const { documentation, fallback, modifier, name, type } = storageFn;
    // Convert the old type to the new type: there is one new field
    // called `hasher`, which we initialize to xxHash (the default in
    // v3).
    const [newType, index] = type.isPlain
        ? [type.asPlain, 0]
        : type.isMap
            ? [codec_1.createType(registry, 'MapTypeV4', {
                    hasher: codec_1.createType(registry, 'StorageHasherV4', 'Twox128'),
                    key: type.asMap.key,
                    value: type.asMap.value,
                    linked: type.asMap.linked
                }), 1]
            : [codec_1.createType(registry, 'DoubleMapTypeV4', {
                    hasher: codec_1.createType(registry, 'StorageHasherV4', 'Twox128'),
                    key1: type.asDoubleMap.key1,
                    key2: type.asDoubleMap.key2,
                    value: type.asDoubleMap.value,
                    key2Hasher: type.asDoubleMap.key2Hasher
                }), 2];
    return codec_1.createType(registry, 'StorageFunctionMetadataV4', {
        documentation,
        fallback,
        name,
        modifier,
        type: codec_1.createType(registry, 'StorageFunctionTypeV4', newType, index)
    });
}
/** @internal */
function toV4(registry, { modules }) {
    return codec_1.createType(registry, 'MetadataV4', {
        modules: modules.map(({ calls, events, name, prefix, storage }) => codec_1.createType(registry, 'ModuleMetadataV4', {
            calls,
            events,
            name,
            prefix,
            storage: storage.isSome
                ? new codec_1.Option(registry, 'Vec<StorageFunctionMetadataV4>', storage.unwrap().map((v) => toV4StorageFunction(registry, v)))
                : undefined
        }))
    });
}
exports.default = toV4;
