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

let _navigator

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  )
}

function resetWithRoute(routeName, params) {
  _navigator.dispatch(
    StackActions.reset({
      index: 1,
      actions: [
        NavigationActions.navigate({routeName: 'BottomTab'}),
        NavigationActions.navigate({routeName, params})
      ]
    })
  )
}

function goBack() {
  _navigator.dispatch(NavigationActions.back())
}


function getCurrentScreenName() {
  return _getCurrentScreen().routeName
}

function _getCurrentScreen(nav) {
  if (nav === undefined)
    nav = _navigator.state.nav
  if (nav.routes) {
    return _getCurrentScreen(nav.routes[nav.index])
  }
  return nav
}

export default {
  navigate,
  setTopLevelNavigator,
  resetWithRoute,
  goBack,
  getCurrentScreenName,
}