import { NavigationActions, StackActions } from 'react-navigation';

import { DrawerActions } from 'react-navigation-drawer';

import * as types from './../actions/types';
import AppNavigator from '../navigation/AppNavigation';

let Navigator: any = AppNavigator;

if (!AppNavigator) {
  Navigator = {
    router: {
      getStateForAction: (data: any) => data,
      getActionForPathAndParams: () => null
    }
  };
}
function navigate({ routeName, params, id }: any) {
  if (routeName == 'DrawerOpen') return DrawerActions.openDrawer();
  else if (routeName == 'DrawerClose') return DrawerActions.closeDrawer();
  else return NavigationActions.navigate({ routeName, params, id });
}

const initialState = AppNavigator.router.getStateForAction(
  Navigator.router.getActionForPathAndParams('Splash')
);

const reducer = (state: any = initialState, action: any) => {
  switch (action.type) {
    case 'Navigation/NAVIGATE':
      return AppNavigator.router.getStateForAction(navigate(action), state);
    case types.GO_BACK:
    case 'Navigation/BACK':
      return AppNavigator.router.getStateForAction(
        NavigationActions.back(action),
        state
      );
    case 'Navigation/OPEN_DRAWER':
      return AppNavigator.router.getStateForAction(
        DrawerActions.openDrawer(),
        state
      );
    case 'Navigation/CLOSE_DRAWER':
      return AppNavigator.router.getStateForAction(
        DrawerActions.closeDrawer(),
        state
      );
    case types.LOGIN_SUCCESS:
    case types.NAVIGATE_TO_HOME:
      return AppNavigator.router.getStateForAction(
        StackActions.reset({
          index: 0,
          actions: [NavigationActions.navigate({ routeName: 'DashBoard' })]
        }),
        state
      );
    case types.LOGOUT_SUCCESS:
      return AppNavigator.router.getStateForAction(
        StackActions.reset({
          index: 0,
          actions: [NavigationActions.navigate({ routeName: 'Login' })]
        }),
        state
      );
    case types.NAVIGATE_TO_BOOK_REQUEST_DETAILS:
      return AppNavigator.router.getStateForAction(
        NavigationActions.navigate({ routeName: 'BookRequestDetails' }),
        state
      );
    case types.BOOK_HISTORY_DETAILS_SUCCESS:
      return AppNavigator.router.getStateForAction(
        NavigationActions.navigate({ routeName: 'BookHistoryDetails' }),
        state
      );

    default:
      return state;
  }
};

export default reducer;
