import { useContext, useState, useEffect, useRef } from 'react';
import { ClientContext } from '../contexts/clientProvider';
import { Token } from '../core/token';
import { Project } from '../core/project';

export const useTokenContext = ({
    tokenId,
    project,
}: {
    tokenId: number;
    project?: Project;
}) => {
    const client = useContext(ClientContext);
    const [loaded, setLoaded] = useState(false);
    const [token, setToken] = useState<Token>(null);
    const [error, setError] = useState(null);
    const [lastTokenId, setLastTokenId] = useState(null);
    const reloadToken = useRef(null);

    useEffect(() => {
        if (!client.loaded || tokenId === undefined) return;
        if (tokenId === lastTokenId && lastTokenId !== null) return;

        const main = async () => {
            try {
                setLoaded(false);
                const token = await (
                    (project || client.project) as Project
                ).getToken(tokenId);
                if (token.loadError) {
                    setError(token.loadError);
                }
                setToken(token);
                setLoaded(true);
            } catch (error) {
                setError(error);
            } finally {
                setLastTokenId(tokenId);
            }
        };
        reloadToken.current = main;
        main();
    }, [client, tokenId, project, lastTokenId]);

    return {
        loaded,
        token,
        error,
        reloadToken,
    };
};
