import { BlockFilter, constructBlock, extractBlock, isResolvedBlock } from '@coinweb/contract-kit';

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

export const blockOp = (filters: BlockFilter[]) =>
  new Promise<[BlockFilter, boolean][] | null>((resolve, reject) => {
    try {
      const { op, isOp } = shiftResolvedOp();

      if (!isOp) {
        pushAwaitedOp(constructBlock(filters));
      } else {
        if (op && !isResolvedBlock(op)) {
          throw new Error('Block operation not found');
        }

        const result = op && extractBlock(op);

        resolve(result);
      }
    } catch (error) {
      reject(error);
    }
  });
