import memoize from "memoize";
import ManyKeysMap from "many-keys-map";
import { isFunction } from "./isFunction";
import { getByKeyArray } from "./getByKeyArray";
import { recursiveDestructuringNestedUpdater } from "./recursiveDestructuringNestedUpdater";
export function rawProvideNestedSetState(rootUpdater, ...keys) {
    return function (setNestedStateAction) {
        rootUpdater((prevRootState) => {
            let nextNestedState;
            if (isFunction(setNestedStateAction)) {
                nextNestedState = setNestedStateAction(getByKeyArray(prevRootState, ...keys));
            }
            else {
                nextNestedState = setNestedStateAction;
            }
            const finalState = recursiveDestructuringNestedUpdater(prevRootState, keys, nextNestedState);
            return finalState;
        });
    };
}
export const provideNestedSetState = memoize(rawProvideNestedSetState, {
    cacheKey: (arguments_) => arguments_,
    cache: new ManyKeysMap(),
});
