import * as React from "react";
import { BackHandler, Platform } from "react-native";
import {
  createReactNavigationReduxMiddleware,
  reduxifyNavigator
} from "react-navigation-redux-helpers";
import { connect } from "react-redux";
import AppNavigation from "./AppNavigation";
import {ApplicationState} from "../Redux/index";

createReactNavigationReduxMiddleware(
  "root",
  (state:ApplicationState) => state.nav
);


const ReduxAppNavigator = reduxifyNavigator(AppNavigation , "root");

interface ReduxNavigationProps {
  dispatch(object:object):any,
  nav?:any

}

class ReduxNavigation extends React.Component<ReduxNavigationProps> {

  componentDidMount() {
    if (Platform.OS === "ios") return;
    BackHandler.addEventListener("hardwareBackPress", ()=>{
      const { dispatch, nav } = this.props;
      // change to whatever is your first screen, otherwise unpredictable results may occur
      if (nav.routes.length === 1 && (nav.routes[0].routeName === "LaunchScreen")) {
        return false;
      }
      // if (shouldCloseApp(nav)) return false
      dispatch({ type: "Navigation/BACK" });
      return true;
    });
  }

  componentWillUnmount() {
    if (Platform.OS === "ios") return;
    BackHandler.removeEventListener("hardwareBackPress",undefined);
  }

  render() {
    return <ReduxAppNavigator dispatch={this.props.dispatch} state={this.props.nav} />
  }

}

const mapStateToProps = state => ({
  nav: state.nav ,
  isDarkMode:state.appSettings.isDarkMode

});
export default connect(mapStateToProps)(ReduxNavigation);
