import { useContext } from "react";
import { MemoryContext } from "./MemoryProvider";

export function useMemory<T>(selector : string, def : T, writable : boolean = true) : [T, (value: T | ((prevValue: T) => T)) => void] {
    const {memory, setMemory} = useContext(MemoryContext);
    const value = () => {
        if(memory[selector] == undefined){
            return def;
        }
        return memory[selector];
    };
    const setValue = (value: T | ((prevValue: T) => T)) => {
        if (!writable && memory[selector] == undefined) {
            return;
        }
        const newValue = typeof value === "function" ? 
            (value as (prevValue: T) => T)(memory[selector] ?? def) 
                : value;
        setMemory((prev : any) => ({
            ...prev,
            [selector]: typeof value === "function"
                ? (value as (prevValue: T) => T)(prev[selector] ?? def)
                : newValue,
        }));
    }
    return [value(), setValue];
}