/**
 * @flow
 */

import { NavigationActions } from 'react-navigation';
import NavigationStack from './navigationStack';
import { initialRouteName } from '../utils/constants';
import toast from '../components/Toast';
import { PUSH, POP, TAB } from './actions';

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

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

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

const nav = (state = initialState, action) => {
  console.log('nav:',action)
  switch (action.type) {
  case PUSH:
    return NavigationStack.router.getStateForAction(ActionForNativePage(action), state);
  case POP:
    if (action.pageName) {
      return NavigationStack.router.getStateForAction(ActionForNativePage(action), 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;
