import { getObservableClient } from "@polkadot-api/observable-client"
import { createClient } from "@polkadot-api/substrate-client"
import { decAnyMetadata, unifyMetadata } from "@polkadot-api/substrate-bindings"
import { helper } from "@substrate/light-client-extension-helpers/extension-page"

import { getLookupFn } from "@polkadot-api/metadata-builders"
import { getViewBuilder } from "@polkadot-api/view-builder"

export const decodeCallData = async (chainId: string, callData: string) => {
    const chains = await helper.getChains()
    const chain = chains.find(({ genesisHash }) => genesisHash === chainId)
    if (!chain) throw new Error("unknown chain")
    const client = createClient(chain.provider)
    try {
        const metadata = await new Promise((resolve, reject) =>
                client._request("state_getMetadata", [], {
                    onSuccess: resolve,
                    onError: reject,
                }),
            )
            .then(r => r)
            .catch(_ => undefined)

        const convertedMetadata = unifyMetadata(decAnyMetadata(metadata))
        return getViewBuilder(getLookupFn(convertedMetadata)).callDecoder(callData)
    } catch {
        return undefined
    }
}
