import React, { createContext } from 'react';
import PropTypes from 'prop-types';
import { useTokenContext } from '../effects/useTokenContext';
import { Token } from '../core/token';
import { Project } from '../core/project';

export interface TokenContextType {
    token: Token;
    loaded: boolean;
    error: Error;
}

export const TokenContext = createContext({
    token: null,
    loaded: false,
    error: null,
} as TokenContextType);

function TokenContextProvider({
    children,
    tokenId = null,
    project = null,
    loadingComponent = null,
}: {
    children: any;
    tokenId?: number;
    project?: Project;
    loadingComponent?: any;
}) {
    const { token, error, loaded } = useTokenContext({
        tokenId,
        project,
    });

    return (
        <TokenContext.Provider
            value={
                {
                    token,
                    error,
                    loaded,
                } as TokenContextType
            }
        >
            <>
                {loadingComponent ? (
                    <>{loaded ? { children } : loadingComponent}</>
                ) : (
                    <>{children}</>
                )}
            </>
        </TokenContext.Provider>
    );
}

TokenContextProvider.propTypes = {
    children: PropTypes.any,
};

export default TokenContextProvider;
