import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { RequestStates } from '../../types';
var ReloadFacetSignalContext = createContext(null);
var ReloadFacetActionContext = createContext(null);
export var ReloadFacetProvider = function (_a) {
    var children = _a.children;
    var _b = useState(0), refreshSignal = _b[0], setRefreshSignal = _b[1];
    var refreshAll = useCallback(function () {
        setRefreshSignal(function (signal) { return signal + 1; });
    }, [setRefreshSignal]);
    return (React.createElement(ReloadFacetActionContext.Provider, { value: refreshAll },
        React.createElement(ReloadFacetSignalContext.Provider, { value: refreshSignal }, children)));
};
export var useReloadAllFacets = function () {
    var refreshAll = useContext(ReloadFacetActionContext);
    if (refreshAll === undefined) {
        throw new Error('useReloadAllFacets must be used within a ReloadFacetProvider');
    }
    return refreshAll;
};
export var useReloadFacet = function (_a) {
    var state = _a.state, reload = _a.reload;
    var refreshSignal = useContext(ReloadFacetSignalContext);
    if (refreshSignal === undefined) {
        throw new Error('useReloadFacet must be used within a ReloadFacetProvider');
    }
    useEffect(function () {
        if (state === RequestStates.LOADED || state === RequestStates.ERROR) {
            reload();
        }
    }, [refreshSignal]);
};
