import useSWR from "swr"
import { getDynamicBuilder, getLookupFn } from "@polkadot-api/metadata-builders"

import { useUnstableProvider } from "./useUnstableProvider"
import { useMetadata } from "./useMetadata"

export const useExistentialDeposit = () => {
    const { chainId } = useUnstableProvider()
    const metadata = useMetadata()
    const { data: existentialDeposit } = useSWR(
        chainId && metadata
            ? ["existentialDeposit", chainId, metadata]
            : null,
        ([_, chainId, metadata]) => {
            const builder = getDynamicBuilder(getLookupFn(metadata))
            const codec = builder.buildConstant("Balances", "ExistentialDeposit")
            const constants = metadata?.pallets?.find(obj => obj.name === "Balances")?.constants
            const value = constants?.find(obj => obj.name === "ExistentialDeposit")?.value
            return value ? codec.dec(value) : undefined
        }
    )
    return existentialDeposit
}
