import { Claim, Context, extractContractArgs, extractRead, OrdJson, ResolvedOperation } from '@coinweb/contract-kit';

import { TypedClaim } from '../../shared';

let contractArguments: ResolvedOperation[] | null = null;

export const getReadClaimByIndex =
  <TClaim extends Claim = TypedClaim<OrdJson>>(context: Context) =>
  (index: number) => {
    if (!contractArguments) {
      contractArguments = extractContractArgs(context.tx);
    }

    if (!contractArguments[index]) {
      return null;
    }

    return (extractRead(contractArguments[index])?.[0]?.content as TClaim) || null;
  };
