import React from 'react';
import {
    ToastAndroid,
    BackHandler,
    DeviceEventEmitter,
    Platform
} from 'react-native';
import {connect} from 'react-redux';
import {
    createReduxContainer,
    createReactNavigationReduxMiddleware,
    createNavigationReducer,
} from 'react-navigation-redux-helpers';
import {
    NavigationActions,
} from 'react-navigation';

import RootStack from './root'

export const routerReducer = createNavigationReducer(RootStack);

export const routerMiddleware = createReactNavigationReduxMiddleware(
    Platform.OS === 'ios' ? (state) => state.router : state => state.nav,
);
const AppStack = createReduxContainer(RootStack, 'root');
let lastBackPressed = 0;

function getActiveRouteName(navigationState) {
    if (!navigationState) {
        return null;
    }
    const route = navigationState.routes[navigationState.index];
    if (route.routes) {
        return getActiveRouteName(route);
    }
    return route.routeName;
}

@connect(({app, router}) => ({app, router}))
class Router extends React.PureComponent {
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.backHandle);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.backHandle);
    }

    backHandle = () => {
        const currentScreen = getActiveRouteName(this.props.router);
        if (currentScreen === 'Main') {
            return true;
        }
        const MainRouteNames = ['DesktopHome',];
        if (MainRouteNames.indexOf(currentScreen) === -1) {
            this.props.dispatch(NavigationActions.back());
            return true;
        } else {
            if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
                //最近2秒内按过back键，可以退出应用。
                return false;
            }
            lastBackPressed = Date.now();
            ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
            return true;
        }

    };

    render() {
        const {dispatch, router} = this.props;
        return <AppStack
            dispatch={dispatch}
            state={router}
        />;
    }
}

export default Router;
