import readline from "readline";

let initialized = false;

export function initKeypress() {
  if (!initialized) {
    readline.emitKeypressEvents(process.stdin);
    initialized = true;
  }
  process.stdin.removeAllListeners("keypress");
  if (process.stdin.isTTY) {
    process.stdin.setRawMode(true);
  }
}

export function onKey(handler) {
  process.stdin.on("keypress", handler);
}

export function stopKeypress() {
  process.stdin.removeAllListeners("keypress");
  if (process.stdin.isTTY) {
    process.stdin.setRawMode(false);
  }
}

export function waitForKey(message = "按任意键返回...") {
  return new Promise(resolve => {
    console.log("\n" + message);
    initKeypress();
    const handler = () => {
      stopKeypress();
      resolve();
    };
    process.stdin.once("keypress", handler);
  });
}
