import { constructTake, extractTake, isResolvedTake, Claim, ClaimKey } from '@coinweb/contract-kit';

import { TypedClaim } from '../../../types';
import { pushAwaitedOp } from '../awaited';
import { shiftResolvedOp } from '../resolved';

export const takeOp = <TClaim extends Claim = TypedClaim>(key: ClaimKey) =>
  new Promise<TClaim | null>((resolve, reject) => {
    try {
      const { op, isOp } = shiftResolvedOp();

      if (!isOp) {
        pushAwaitedOp(constructTake(key));
      } else {
        if (op && !isResolvedTake(op)) {
          throw new Error('Take operation not found');
        }

        const claim = op && extractTake(op);
        resolve(claim as TClaim | null);
      }
    } catch (error) {
      reject(error);
    }
  });
