"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");
const hasherMap = new Map([
    ['blake2_128', 'Blake2_128'],
    ['blake2_256', 'Blake2_256'],
    ['twox_128', 'Twox128'],
    ['twox_256', 'Twox256'],
    ['twox_64_concat', 'Twox64Concat']
]);
/** @internal */
function toStorageHasher(registry, text) {
    const mapped = hasherMap.get(text.toString());
    util_1.assert(mapped, `Invalid Storage hasher: ${text.toString()}`);
    return codec_1.createType(registry, 'StorageHasherV5', mapped);
}
/** @internal */
function toV5StorageFunction(registry, storageFn) {
    const { documentation, fallback, modifier, name, type } = storageFn;
    const [newType, index] = type.isPlain
        ? [type.asPlain, 0]
        : type.isMap
            ? [type.asMap, 1]
            : [codec_1.createType(registry, 'DoubleMapTypeV5', {
                    hasher: type.asDoubleMap.hasher,
                    key1: type.asDoubleMap.key1,
                    key2: type.asDoubleMap.key2,
                    value: type.asDoubleMap.value,
                    key2Hasher: toStorageHasher(registry, type.asDoubleMap.key2Hasher)
                }), 2];
    return codec_1.createType(registry, 'StorageFunctionMetadataV5', {
        documentation,
        fallback,
        name,
        modifier,
        type: codec_1.createType(registry, 'StorageFunctionTypeV5', newType, index)
    });
}
/** @internal */
function toV5(registry, { modules }) {
    return codec_1.createType(registry, 'MetadataV5', {
        modules: modules.map(({ calls, events, name, prefix, storage }) => codec_1.createType(registry, 'ModuleMetadataV5', {
            name,
            prefix,
            storage: storage.isSome
                ? new codec_1.Option(registry, 'Vec<StorageFunctionMetadataV5>', storage.unwrap().map((v) => toV5StorageFunction(registry, v)))
                : undefined,
            calls,
            events
        }))
    });
}
exports.default = toV5;
