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'
import {getUrlParameter} from './utils/index';

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() {
        DeviceEventEmitter.addListener('PushFromAndroid', this.handleAndroidMessage.bind(this));
        BackHandler.addEventListener('hardwareBackPress', this.backHandle);
    }

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

    handleAndroidMessage(message) {
        const type = getUrlParameter('type', message);
        const targetId = getUrlParameter('target_id', message);
        switch (type) {
            case "ASKEXPERT": //学霸问题
                this.props.dispatch(NavigationActions.navigate({
                        routeName: 'QuestionDetail',
                        params: {question_id: targetId,},
                        action: NavigationActions.navigate({routeName: 'DiscoverHome'})
                    })
                );
                break;
        }
    }

    backHandle = () => {
        const currentScreen = getActiveRouteName(this.props.router);
        if (currentScreen === 'Main') {
            return true;
        }
        const MainRouteNames = ['SalesHome', 'MaintenanceHome', 'MineHome', 'ReportHome', 'Login',];
        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;
