import React, { PropsWithChildren, useMemo } from 'react';
import { OnRequestSources, ResourceBrowserPlugin } from '../types';

import pMemoize from 'p-memoize';
import ExpiryMap from 'expiry-map';

export type ResourceBrowserContextProps = {
    onRequestSources: OnRequestSources;
    searchEnabled: boolean;
    plugins: Array<ResourceBrowserPlugin>;
};

/**
 * @internal Direct usage of this object is discouraged. It will be privated in a future major version.
 * Please use ResourceBrowserContextProvider instead.
 */
export const ResourceBrowserContext = React.createContext<ResourceBrowserContextProps>({
    onRequestSources: () => {
        throw new Error('onRequestSources has not been configured.');
    },
    searchEnabled: false,
    plugins: [],
});

export const ResourceBrowserContextProvider = (props: PropsWithChildren<{ value: ResourceBrowserContextProps }>) => {
    const CACHE_DURATION = 30000; // 30 seconds
    const {
        value: { onRequestSources, ...other },
        children,
    } = props;
    const cache = new ExpiryMap(CACHE_DURATION);
    const memoized = useMemo(
        () => ({
            onRequestSources: pMemoize(onRequestSources, {
                cache,
                cacheKey: () => 'onRequestSources',
            }),
        }),
        [onRequestSources],
    );

    return <ResourceBrowserContext.Provider value={{ ...memoized, ...other }}>{children}</ResourceBrowserContext.Provider>;
};
