import API from "../../Utils/API/API";
import ModelAPI from "../../Utils/ModelAPI/ModelAPI";
import SideMenuItem from "./SideMenuItem";
import React, { useEffect, useState, useCallback } from "react";
import GlobalEvents from "../../Utils/GlobalEvents";
export const REFRESH_SIDEBAR_COUNT_EVENT = "REFRESH_SIDEBAR_COUNTS";
const CountModelSideMenuItem = (props) => {
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState("");
    const [count, setCount] = useState(0);
    const fetchCount = useCallback(async () => {
        if (!props.modelType) {
            return;
        }
        if (!props.countQuery) {
            return;
        }
        setError("");
        setIsLoading(true);
        if (props.onCountFetchInit) {
            props.onCountFetchInit();
        }
        try {
            const count = await ModelAPI.count({
                modelType: props.modelType,
                query: props.countQuery,
                requestOptions: props.requestOptions,
            });
            setCount(count);
            setError("");
        }
        catch (err) {
            setError(API.getFriendlyMessage(err));
        }
        setIsLoading(false);
    }, [
        props.modelType,
        props.countQuery,
        props.requestOptions,
        props.onCountFetchInit,
    ]);
    useEffect(() => {
        fetchCount().catch((err) => {
            setError(API.getFriendlyMessage(err));
        });
    }, [fetchCount]);
    // Listen for global refresh events
    useEffect(() => {
        const handleRefresh = () => {
            fetchCount().catch((err) => {
                setError(API.getFriendlyMessage(err));
            });
        };
        GlobalEvents.addEventListener(REFRESH_SIDEBAR_COUNT_EVENT, handleRefresh);
        return () => {
            GlobalEvents.removeEventListener(REFRESH_SIDEBAR_COUNT_EVENT, handleRefresh);
        };
    }, [fetchCount]);
    return (React.createElement(SideMenuItem, { link: props.link, badge: !isLoading && !error ? count : undefined, badgeType: props.badgeType, icon: props.icon, className: props.className }));
};
export default CountModelSideMenuItem;
//# sourceMappingURL=CountModelSideMenuItem.js.map