import { ResolvedOp } from '../../types';

const resolvedOps: ResolvedOp[] = [];

let usedOps: ResolvedOp[] = [];
let isSavingUsed = false;
let isFreezed = false;

export const pushResolvedOp = (op: ResolvedOp | ResolvedOp[]) => {
  if (isFreezed) {
    return;
  }

  if (Array.isArray(op)) {
    resolvedOps.push(...op);
  } else {
    resolvedOps.push(op);
  }
};

export const shiftResolvedOp = () => {
  const result = {
    isOp: resolvedOps.length > 0 && !isFreezed,
    op: isFreezed ? undefined : resolvedOps.shift(),
  } as
    | {
        isOp: true;
        op: ResolvedOp | null;
      }
    | {
        isOp: false;
        op: undefined;
      };

  if (isSavingUsed && result.op) {
    usedOps.push(result.op);
  }

  console.log('shiftResolvedOp: ', JSON.stringify(result));

  return result;
};

export const getUsedOps = () => usedOps;

export const startSavingUsedOps = () => {
  usedOps = [];
  isSavingUsed = true;
};

export const stopSavingUsedOps = () => {
  isSavingUsed = false;
};

export const freezeResolvedOps = () => {
  isFreezed = true;
};

export const unfreezeResolvedOps = () => {
  isFreezed = false;
};
