import {ActionReducer, INIT} from '@ngrx/store';
import {CustomAppStates} from '../custom.app.states';
import {MetaReducer} from '@ngrx/store';



export const hydrationMetaReducer = (
    reducer: ActionReducer<CustomAppStates>
): ActionReducer<CustomAppStates> => {
    return (state, action) => {
        if (action.type === INIT) {
            const storageValue = localStorage.getItem('lib-state');
            if (storageValue) {
                try {
                    return JSON.parse(storageValue);
                } catch {
                    localStorage.removeItem('lib-state');
                }
            }
        }
        const nextState = reducer(state, action);
        localStorage.setItem('lib-state', JSON.stringify(nextState));
        return nextState;
    };
};

export const metaReducers: MetaReducer[] = [hydrationMetaReducer];
