import { useCallback } from "react";
import { useParams } from "react-router-dom";

import { BlockerModel } from "../models/blockerModel.js";
import { useStores } from "../store/stores.js";

const useRouteBlocker = () => {
    const params = useParams();
    const { cookieStore } = useStores();

    // Get blocker or return draft object
    const blockerId = +params.blocker;
    const id = isNaN(+blockerId) ? 0 : +blockerId;
    const queried = !!blockerId;
    const blocker = cookieStore.blockers.entries.get(id) || new BlockerModel(cookieStore.blockers, { id: 0 });

    const link = `#/blocker`;
    const editLink = useCallback(({ key }: BlockerModel) => `#/blocker/edit/${key}`, [blocker]);
    const addLink = `#/blocker/new`;

    return { blocker, id, queried, fetched: blocker.key !== 0, link, editLink, addLink };
};

export { useRouteBlocker };
