import React, {Component} from 'react';
import {Alert, View} from 'react-native';
import {readUser, updatePosition, updateUserData} from './../../webservice/AuthApi';
import {responsiveHeight} from 'react-native-responsive-dimensions';
import Icon from 'react-native-vector-icons/FontAwesome5'
import Button from 'apsl-react-native-button'
import I18n from 'react-native-i18n'
import {IlinkEmitter} from "../../utils/events";
import Geolocation from 'react-native-geolocation-service';

let theme = require('./../../utils/theme.json');

const route = require('./../../route.json')

require('./../../utils/Translations')

const height = responsiveHeight(100) - 250;
export default class UpdateInformations extends Component {
    static navigatorStyle = {
        navBarHidden: false,
        navBarBackgroundColor: theme.primaryDark,
        navBarTextColor: 'white',
        navBarButtonColor: 'white',
        drawUnderStatusBar: false,
        statusBarColor: theme.primaryDarkAdvanced,
        statusBarTextColorScheme: 'light',
    };

    static options(passProps) {
        return {
            statusBar: {
                drawBehind: false
            },
            topBar: {
                title: {
                    text: "Mise à jour des informations",
                    color: "white"
                },

                background: {
                    color: theme.primaryDark

                }
            }
        }
    }

    static navigationOptions = ({navigation}) => {
        return {
            headerTitle: I18n.t('CHANGE_INFORMATION'),
            drawerIcon: ({tintColor}) => (
                <Icon
                    name={'user'}
                    size={24}
                />
            ),
        }
    };

    constructor(props) {
        super(props)

        this.state = this.initiateItems()
        IlinkEmitter.on("langueChange", this.updateLangue.bind(this))
        this.showUserState()
    }

    async showUserState() {
        const user = await readUser()
        this.setState({user: user})
        if (user.longitude <= 0 && user.latitude <= 0) {
            Alert.alert(I18n.t('TITLE_NEED_POSITION'), I18n.t('TEXT_NEED_POSITION'), [{text: 'Ok'}])
        }
    }

    updateLangue() {
        this.props.navigation.setParams({name: I18n.t('CHANGE_INFORMATION')})
        this.forceUpdate()
    }

    render() {
        return (
            <View style={{flex: 1, backgroundColor: theme.primary}}>
                <Button
                    isLoading={this.state.positionEnabled}
                    style={{
                        backgroundColor: theme.primaryDark,
                        marginTop: responsiveHeight(5),
                        height: responsiveHeight(7),
                        marginRight: 10,
                        marginLeft: 10,
                        borderColor: 'transparent'
                    }} textStyle={{color: "white", fontSize: 20, fontWeight: 'bold'}}
                    onPress={() => this.onClickUpdatePosition()}>{I18n.t('UPDATE_POSITION_TEXT')}</Button>
            </View>);
    }

    initiateItems() {
        return {
            positionEnabled: false,
        }
    }

    onClickUpdatePosition() {
        this.setState({positionEnabled: true});
        Geolocation.getCurrentPosition((position) => {
            console.log("CURRENT POSITION", position);
            const myPosition = position.coords;
            updatePosition(myPosition.longitude, myPosition.latitude).then((response) => {
                var title = '';
                var message = '';
                this.setState({positionEnabled: false})
                console.log(response.error)
                if (response.error === undefined) {
                    updateUserData({longitude: myPosition.longitude, latitude: myPosition.latitude})
                    message = I18n.t('POSITION_UPDATE_SUCCESS_TEXT')
                    title = I18n.t('UPDATE_SUCCESS');
                } else {
                    title = I18n.t("TITLE_UPDATE_POSITION_FAILED")
                    switch (response.error) {
                        case -3:
                            message = I18n.t('TEXT_UDATE_POSITION_FAILED_1');
                            break
                        case -2:
                            message = I18n.t('TEXT_UDATE_POSITION_FAILED_2');
                            break;
                    }

                }
                Alert.alert(title, message, [{
                    text: "Ok", onPress: () => {
                        this.props.navigation.popToTop()
                    }
                }]);
            }).catch((e) => {
                console.log(e);
                this.setState({positionEnabled: false})
            })
        }, (e) => {
            console.log(e);
            Alert.alert(I18n.t('ERROR_LABEL'), e.message, [{
                text: "Ok", onPress: () => {
                    this.props.navigation.popToTop();
                }
            }]);
        }, this.props.geolocationOptions);

    }
}