// @flow
import { NavigationActions } from 'react-navigation';
import type { NavigationParams, NavigationRoute } from 'react-navigation/src/TypeDefinition';

let _container; // eslint-disable-line

function setContainer(container: Object) {
  _container = container;
}

function back() {
  _container.props.navigation.dispatch(NavigationActions.back());
}

function reset(routeName: string, params?: NavigationParams) {
  _container.props.navigation.dispatch(NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({
        routeName,
        params,
      }),
    ],
  }));
}

function navigate(routeName: string, params?: NavigationParams) {
  _container.props.navigation.dispatch(NavigationActions.navigate({
    routeName,
    params,
  }));
}

function navigateDeep(actions: { routeName: string, params?: NavigationParams }[]) {
  _container.props.navigation.dispatch(actions.reduceRight(
    (prevAction, action): any =>
      NavigationActions.navigate({
        routeName: action.routeName,
        params: action.params,
        action: prevAction,
      }),
    undefined,
  ));
}

function getCurrentRoute(): NavigationRoute | null {
  if (!_container || !_container.state.nav) {
    return null;
  }

  return _container.state.nav.routes[_container.state.nav.index] || null;
}

export default {
  setContainer,
  navigateDeep,
  navigate,
  back,
  reset,
  getCurrentRoute,
};
