import { Action } from 'mweb/common/actions/root';
import { NAVIGATION_UPDATED_LOCATION_ACTION_TYPE } from 'mweb/common/actions/navigation';
import { Location } from 'mweb/common/reducers/app';

interface Reducer<S> {
  (state: S | undefined, action: Action): S;
}

export function resetPageReducerOnNavigation<S>(
  reducer: Reducer<S>,
  location: Location,
): Reducer<S> {
  return function(state: S, action: Action): S {
    if (action.type === NAVIGATION_UPDATED_LOCATION_ACTION_TYPE) {
      if (action.payload.location !== location) {
        return reducer(undefined, action);
      }
    }

    return reducer(state, action);
  };
}
