import { Controller, PID } from "@tingwu/core";

export const generateGetJustFixPid = (controller: Controller) => {
  let destroyGetJustFixPid: (() => void) | undefined;
  let lastPid: PID | undefined;
  let timer: ReturnType<typeof setTimeout>;

  function listen() {
    destroyGetJustFixPid = controller.on("addFixParagraph", () => {
      clearTimeout(timer);
      const pids = controller.getPids();
      lastPid = pids.length > 0 ? pids[pids.length - 1] : undefined;
      timer = setTimeout(() => {
        lastPid = undefined;
      }, 500);
    });
  }

  function getJustFixPid() {
    return lastPid;
  }

  listen();

  return {
    getJustFixPid,
    destroyGetJustFixPid,
  };
};
