import { NgModule } from '@angular/core';
import { StoreModule, MetaReducer, ActionReducer, INIT } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { storeFreeze } from 'ngrx-store-freeze';
import { environment } from '../environments/environment';
import { RootState } from './store/root.state';
import { rootReducer } from './store/root.reducer';
import { EffectsModule } from '@ngrx/effects';
import { SearchEffects } from './store/customer';
import { HistoryEffects } from '@shelf-store/history';
import { DetailsEffects } from '@shelf-store/details';

// TODO: In Service Speichern
export function storeInLocalStorage(reducer: ActionReducer<any>): ActionReducer<any> {
  const lsKey = 'ISA_NGRX_STATE';

  return function (state, action) {
    if (action.type === INIT) {
      const storedState = JSON.parse(localStorage.getItem(lsKey));
      if (storedState) {
        return reducer(storedState, action);
      }
    }
    const nextState = reducer(state, action);
    localStorage.setItem(lsKey, JSON.stringify(nextState));
    return nextState;
  };
}

export const metaReducers: MetaReducer<RootState>[] = !environment.production ? [storeFreeze, storeInLocalStorage] : [storeInLocalStorage];

@NgModule({
  imports: [
    StoreModule.forRoot(rootReducer, { metaReducers }),
    EffectsModule.forRoot([SearchEffects, HistoryEffects, DetailsEffects]),
    StoreDevtoolsModule.instrument({ name: 'ISA Ngrx Store' }),
  ],
})
export class AppStoreModule {}
