// Copyright 2017-2021 @polkadot/metadata authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey';
import { Metadata } from "../Metadata.js";
import { getUniqTypes } from "./getUniqTypes.js";
/** @internal */

export function decodeLatestSubstrate(registry, version, rpcData, staticSubstrate) {
  it('decodes latest substrate properly', () => {
    const metadata = new Metadata(registry, rpcData);
    registry.setMetadata(metadata);

    try {
      expect(metadata.version).toBe(version);
      expect(metadata[`asV${version}`].modules.length).not.toBe(0);
      expect(metadata.toJSON()).toEqual(staticSubstrate);
    } catch (error) {
      console.error(JSON.stringify(metadata.toJSON()));
      throw error;
    }
  });
}
/** @internal */

export function toLatest(registry, version, rpcData, withThrow = true) {
  it(`converts v${version} to latest`, () => {
    const metadata = new Metadata(registry, rpcData);
    registry.setMetadata(metadata);
    const metadataInit = metadata[`asV${version}`];
    const metadataLatest = metadata.asLatest;
    expect(getUniqTypes(registry, metadataInit, withThrow)).toEqual(getUniqTypes(registry, metadataLatest, withThrow));
  });
}
/** @internal */

export function defaultValues(registry, rpcData, withThrow = true) {
  describe('storage with default values', () => {
    const metadata = new Metadata(registry, rpcData);
    metadata.asLatest.modules.filter(({
      storage
    }) => storage.isSome).forEach(mod => {
      mod.storage.unwrap().items.forEach(({
        fallback,
        name,
        type
      }) => {
        const inner = unwrapStorageType(type);
        const location = `${mod.name.toString()}.${name.toString()}: ${inner}`;
        it(`creates default types for ${location}`, () => {
          expect(() => {
            try {
              registry.createType(inner, fallback);
            } catch (error) {
              const message = `${location}:: ${error.message}`;

              if (withThrow) {
                throw new Error(message);
              } else {
                console.warn(message);
              }
            }
          }).not.toThrow();
        });
      });
    });
  });
}