import {
  constructContinueTx,
  constructContractIssuer,
  constructContractRef,
  constructRangeRead,
  constructTake,
  Context,
  extractContractArgs,
  extractContractInfo,
  extractRead,
  getContractId,
} from '@coinweb/contract-kit';

export const mutexUnlock = (context: Context) => {
  const { providedCweb } = extractContractInfo(context.tx);
  const issuer = constructContractIssuer(getContractId(context.tx));
  return [
    constructContinueTx(
      context,
      [],
      [
        {
          callInfo: {
            ref: constructContractRef(issuer, []),
            methodInfo: {
              methodName: '_unlock_exec',
              methodArgs: [],
            },
            contractInfo: {
              providedCweb: (providedCweb ? providedCweb - 1000n : 1000n) / 2n,
              authenticated: null,
            },
            contractArgs: [constructRangeRead(issuer, 'mutex', {}, 10000)],
          },
        },
        {
          callInfo: {
            ref: constructContractRef(issuer, []),
            methodInfo: {
              methodName: '_unlock',
              methodArgs: [],
            },
            contractInfo: {
              providedCweb: (providedCweb ? providedCweb - 1000n : 1000n) / 2n,
              authenticated: null,
            },
            contractArgs: [],
          },
        },
      ]
    ),
  ];
};

export const mutexUnlockExec = (context: Context) => {
  const claim = extractContractArgs(context.tx)[0]!;
  const take = extractRead(claim)![0];
  return [constructContinueTx(context, [constructTake(take.content.key)])];
};
