import * as React from "react";
import { useSessionContext } from "./SessionContext";
const defaultSelector = (value) => value;
export const useApplicationStateSubscription = (selector = defaultSelector) => {
    const { session } = useSessionContext();
    const [value, setValue] = React.useState(() => selector(session.getApplicationState()));
    React.useEffect(() => {
        const subscription = session.on("ApplicationStateValueChanged", () => {
            const newValue = selector(session.getApplicationState());
            if (newValue !== value) {
                setValue(newValue);
            }
        });
        return () => subscription.destroy();
    }, [session]);
    return [value, session.setApplicationState];
};
export const useApplicationStateValueSubscription = (key) => {
    const { session } = useSessionContext();
    const [value, setValue] = React.useState(() => session.getApplicationStateValue(key));
    React.useEffect(() => {
        const subscription = session.on("ApplicationStateValueChanged", () => {
            const newValue = session.getApplicationStateValue(key);
            if (newValue !== value) {
                setValue(newValue);
            }
        });
        return () => subscription.destroy();
    }, [session, key]);
    return [
        value,
        (value) => session.setApplicationStateValue(key, value),
    ];
};
