let abortExecution: ((isFullyExecuted: boolean) => void) | null = null;

export const stopExecution = (isFullyExecuted = false) => {
  console.log('stopExecution');
  abortExecution?.(isFullyExecuted);
};

type ExecTask = () => Promise<void>;

let execQueue: ExecTask[] = [];
export const setNextExec = (task: ExecTask) => (execQueue = [task]);

export const execLoop = async (): Promise<boolean> => {
  const nextExec = execQueue.pop();

  if (nextExec) {
    const execution = new Promise<boolean>((resolve, reject) => {
      abortExecution = resolve;

      nextExec().then(
        () => {
          resolve(true);
        },
        (error) => {
          console.log(error);
          reject(error);
        }
      );
    });

    const isFullyExecuted = await execution;

    if (isFullyExecuted) {
      return true;
    }

    return execLoop();
  }

  return false;
};
