import { useRouter } from 'vue-router';
import { onBeforeUnmount, onDeactivated, onActivated } from 'vue';

export function useNavigate() {
  let isBack = false;
  let isAlive = true;
  const router = useRouter();
  console.log(router);
  function navigateBack() {
    if (isAlive && !isBack) {
      isBack = !isBack;
      router.go(-1);
    }
  }

  function navigateBackV2() {
    if (isAlive && !isBack) {
      isBack = !isBack;
      const match = router.currentRoute.value.matched;
      if (match.length > 1) {
        const backRoute = match[match.length - 2];
        router.push({ name: backRoute.name });
      } else {
        router.go(-1);
      }
    }
  }

  onBeforeUnmount(() => {
    isAlive = false;
  });
  // onActivated(() => {
  //   isAlive = true;
  //   isBack = false;
  // });
  // onDeactivated(() => {
  //   isAlive = true;
  //   isBack = false;
  // });

  return {
    navigateBack,
    navigateBackV2,
  };
}