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

import { opMarker } from '../../global';
import { isResolvedBlockOp, isResolvedSlotOp } from '../../utils';
import { pushAwaitedTask } from '../awaited';
import { shiftResolvedOp } from '../resolved';

export const blockOp = (filters: BlockFilter[]) => {
  console.log('blockOp');
  let opMarkerValue = false;

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

      if (!isOp) {
        pushAwaitedTask(constructBlock(filters));
        opMarkerValue = true;
      } else {
        if (isResolvedSlotOp(op)) {
          console.log('blockOp-slotOp');
          return;
        }

        if (!isResolvedBlockOp(op)) {
          console.log('blockOp-error');
          throw new Error('Block operation not found');
        }

        const result = op && extractBlock(op);

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

  (result as Promise<[BlockFilter, boolean][] | null> & { [opMarker]: boolean })[opMarker] = opMarkerValue;

  return result;
};
