import React from "react";
import { UNSAFE_NavigationContext } from "react-router-dom";

// 估计在 react-router v6 的后续某个版本 usePrompt 会回归
export function usePrompt(message, when = true) {
  let blocker = React.useCallback(
    tx => {
      if (window.confirm(message)) tx.retry();
    },
    [message]
  );

  useBlocker(blocker, when);
}

function useBlocker(blocker, when = true) {
  let { navigator } = React.useContext(UNSAFE_NavigationContext);

  React.useEffect(() => {
    if (!when) return;

    let unblock = navigator.block((tx) => {
      let autoUnblockingTx = {
        ...tx,
        retry() {
          unblock();
          tx.retry();
        }
      };

      blocker(autoUnblockingTx);
    });

    return unblock;
  }, [navigator, blocker, when]);
}
