
import { useEffect, useState, useCallback } from 'react';
import { getCartApiEndpoint } from '../urlTools';

export const useCart = (locale, fetchCart) => {
    const [cart, setCart] = useState({});
    const [isLoading, setIsLoading] = useState(false);

    const finalFetch = useCallback(() => {
        if (fetchCart) {
            return fetchCart();
        }
        const endpoint = getCartApiEndpoint(locale);
        return fetch(endpoint).then(res => res.json());
    }, [locale, fetchCart]);

    // perform ajax fetch whenever we click on search and thus change de search value.
    useEffect(
        () => {
            // keep a closure var to invalidate all effects of this call when a subsequent
            // call is made, or component unmounts
            let isCancelled = false;
            setIsLoading(true);
            const onResolved = finalFetch();
            onResolved.then(result => {
                // this effect has been invalidated, do nothing
                if (isCancelled) {
                    return;
                }
                setIsLoading(false);
                setCart(result);
            });
            return () => {
                isCancelled = true;
            };
        },
        [finalFetch]
    );

    return {
        cart,
        isLoading
    };
};
