/**
 * @flow
 */

import { NavigationActions } from 'react-navigation';
import NavigationStack from './navigationStack';
import { initialRouteName } from '../utils/constants';

import { PUSH, POP, TAB } from './actions';

const ActionForTab = NavigationStack.router.getActionForPathAndParams(initialRouteName);

const ActionForNativePage = pageName => NavigationStack.router.getActionForPathAndParams(pageName);

const initialState = NavigationStack.router.getStateForAction(ActionForTab);

const nav = (state = initialState, action) => {
  switch (action.type) {
  case PUSH:
    return NavigationStack.router.getStateForAction(ActionForNativePage(action.pageName), state);
  case POP:
    if (action.pageName) {
      return NavigationStack.router.getStateForAction(ActionForNativePage(action.pageName), state);
    }
    return NavigationStack.router.getStateForAction(NavigationActions.back(), state);
  case TAB:
    if (action.pageName) {
      return NavigationStack.router.getStateForAction(
        { type: NavigationActions.NAVIGATE, routeName: action.pageName },
        state,
      );
    }
    return state;
  case NavigationActions.NAVIGATE: // 首页tabBar 切换
    return NavigationStack.router.getStateForAction(action, state);

  case NavigationActions.BACK:
    return NavigationStack.router.getStateForAction(NavigationActions.back(), state);
  default:
    return state;
  }
};

export default nav;
