import { PathType } from '@/shared/constants/paths';
import { 
  NavigateOptions,
  To,
  useNavigate as _useNavigate
} from 'react-router';

export type NavigateTo = PathType | -1 | 0;

export const goBackWebview = (goBack: () => void) => {
  if(window.history.state?.idx > 0){
    goBack();
    return;
  }
  else{
    window.close();
  }
  return;
  
};

export const useNavigate = () => {
  const _navigate = _useNavigate();
  
  const navigate = (to: NavigateTo, options?: NavigateOptions): void => {
    const path = typeof to === 'number' ? to : to.toString();
    _navigate(path as To, options);
  };

  const reload = async () => {
    navigate(0);
  };

  const navigateBack = () => goBackWebview(() => _navigate(-1));

  return { navigate, navigateBack, reload };
};
