import React, {Component} from 'react';
import {
    Alert,
    BackHandler,
    FlatList,
    Image,
    PermissionsAndroid,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import PropTypes from 'prop-types';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {Fumi} from 'react-native-textinput-effects'
import * as Animatable from 'react-native-animatable';
import Button from 'apsl-react-native-button';
import MapView, {Marker} from 'react-native-maps';
import {Dropdown} from 'react-native-material-dropdown-v2';
import isEqual from 'lodash/isEqual';
import {getPositionInformation} from './../../webservice/MapService';
import I18n from 'react-native-i18n'
import {material} from 'react-native-typography';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {
    createGeolocatedAccount,
    createUserAccount,
    getCodeInformation,
    getCountryNetwork,
    getListCountriesActive,
    getTownInformationName
} from './../../webservice/AuthApi';
import {MaterialDialog} from "react-native-material-dialog";
import Geolocation from 'react-native-geolocation-service';

const GEOLOCATION_OPTIONS = {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, useSignificantChanges: true};

let theme = require('./../../utils/theme.json');
let route = require('./../../route.json');
let country = require('./../../utils/country_code.json');
/*var Fabric = require('react-native-fabric');

var { Crashlytics } = Fabric;
var { Answers } = Fabric;*/
declare var google;
const propTypes = {
    ...Marker.propTypes,
    coordinate: PropTypes.shape({
        latitude: PropTypes.number.isRequired,
        longitude: PropTypes.number.isRequired,
    }),
    children: PropTypes.node,
    geolocationOptions: PropTypes.shape({
        enableHighAccuracy: PropTypes.bool,
        timeout: PropTypes.number,
        maximumAge: PropTypes.number,
    }),
    heading: PropTypes.number,
    enableHack: PropTypes.bool,
};

const defaultProps = {
    enableHack: false,
    geolocationOptions: GEOLOCATION_OPTIONS,
};

export default class CreateUserStep2 extends Component {
    static navigatorStyle = {
        drawUnderNavBar: true,
        navBarHidden: true,
        drawUnderStatusBar: false,
        statusBarHidden: true,
        statusBarTextColorScheme: 'light',
    };

    static options(passProps) {
        return {
            topBar: {
                visible: false,
                enabled: false,
                drawBehind: true,

            },
            statusBar: {
                drawBehind: true,
                enabled: false,
            }
        }
    }

    constructor(props) {
        super(props);
        const {navigation} = this.props;
        this.type = navigation.getParam("type", 0);
        this.user = navigation.getParam('user', null);
        this.state = this.initState();
    }

    retreiveCodeInformation() {
        const membre = this.state.user.member;
        return new Promise(async (resolve, reject) => {
            let datas = await getCodeInformation(membre)
            resolve(datas)
        })

    }

    initState() {
        return {
            password: null,
            enterPhone: null,
            nameanim: null,
            networksinglePickerVisible: false,
            surnameanim: null,
            passwordanim: null,
            confirmpassanim: null,
            isLoging: false,
            countries: [],
            snackVisible: false,
            snackText: '',
            disableNetwork: false,
            networks: [],
            modalVisible: true,
            select_network: I18n.t("SELECT_NETWORK"),
            user: this.user,
            provider_class: null,
            provider_classes: []

        }
    }

    render() {

        return this.type === 1 ? this.renderUserGeoAccount() : this.renderUserAccount()

    }

    async getNetworks(indicatif) {

        if (indicatif) {
            let result = {}
            try {
                result = await this.retreiveCodeInformation()
                const {category} = result
            } catch (e) {
                result = false
            }
            console.log("Result from second step", result);
            if (result) {
                if (result.child) {
                    this.setState({disableNetwork: true})
                    if (result.network)
                        this.setState({
                            modalVisible: false, networks: [result.network],
                            network: result.network, select_network: I18n.t("YOUR_NETWORK")
                        })

                    else {
                        Alert.alert(I18n.t('TITLE_PROBLE_COME'), "Impossible de recuperer les informations du code parrain", [{
                            text: "Revenir",
                            onPress: () => this.props.navigation.pop()
                        }])
                    }

                    if (result.hasOwnProperty('provider_classes'))
                        this.setState({provider_classes: result.provider_classes});
                } else {
                    console.log("need enable")
                    getCountryNetwork(indicatif).then((result) => {
                        this.reseaux = [];
                        let networks = result;

                        for (let prop in networks) {
                            if (networks[prop] !== "") {
                                this.reseaux.push(networks[prop]);
                            }

                        }
                        this.setState({networks: this.reseaux});
                        this.setState({modalVisible: false})

                    }, (err) => {
                        this.setState({modalVisible: false})
                        this.showErrorDialog()
                    });
                }
            } else {
                getCountryNetwork(indicatif).then((result) => {
                    this.reseaux = [];
                    let networks = result;
                    for (let prop in networks) {
                        if (networks[prop] !== "") {
                            this.reseaux.push(networks[prop]);
                        }
                    }
                    this.setState({networks: this.reseaux});
                    this.setState({modalVisible: false})

                }, (err) => {
                    this.setState({modalVisible: false})
                    this.showErrorDialog()
                });
            }


        } else {
            this.setState({modalDialog: false})
            Alert.alert("Une erreur est survenue", "Impossible de récuperer des informations du pays verifier que votre gps est activé," +
                "et que vous êtes connecté à internet puis ressayer", [{
                text: "Recommencer", onPress: () => {
                    this.setState({modalDialog: true})
                    this.watchLocation()
                }
            }, {
                text: "Annuler", onPress: () => {
                    this.props.navigation.popToTop()
                }
            }])

        }

    }

    showErrorDialog() {
        this.setState({modalDialog: false})
        Alert.alert("Une erreur est survenue", "Impossible de récuperer des informations du pays verifier que votre gps est activé," +
            "et que vous êtes connecté à internet puis ressayer", [{
            text: "Recommencer", onPress: () => {
                this.watchLocation()
            }
        }, {
            text: "Annuler", onPress: () => {
                this.props.navigation.popToTop()
            }
        }])
    }

    componentDidMount() {

        this.mounted = true;
        const {type} = this.props;


        if (this.props.coordinate) return;

        if (Platform.OS === 'android') {
            this.requestCameraPermission();
        } else {
            this.watchLocation();
        }

    }

    async requestCameraPermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                    'title': 'Cool Photo App Camera Permission',
                    'message': 'Cool Photo App needs access to your camera ' +
                        'so you can take awesome pictures.'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.watchLocation();
            } else {
                this.setState({modalDialog: false})
                Alert.alert("Echec à l'autorisation",
                    "L'application n'est pas autorisé à acceder à votre position veuillez verifier que votre GPS est activé et configurer en mode Haute Precision",
                    [{
                        text: "Ok", onPress: () => {
                            this.props.navigation.popToTop()
                        }
                    }])
            }
        } catch (err) {
            this.setState({modalDialog: false})
            Alert.alert("Une erreur est Survenue",
                "Une erreur est survenu lors du demarrage de l'application veuillez relancer l'application",
                [{
                    text: "Ok", onPress: () => {
                        BackHandler.exitApp()
                    }
                }])
        }
    }

    async watchLocation() {
        Geolocation.getCurrentPosition((position) => {
            this.treatPosition(position)
        }, (e) => {
            this.showErrorDialog()
        }, this.props.geolocationOptions);
        if (!this.watchID) {
            Geolocation.watchPosition((position) => {
                this.treatPosition(position)
            }, (e) => {
                this.showErrorDialog()
            }, this.props.geolocationOptions)
        }
    }

    treatPosition(position) {
        const myLastPosition = this.state.myPosition;
        const myPosition = position.coords;

        if (!isEqual(myPosition, myLastPosition)) {
            getPositionInformation(myPosition).then((response) => {
                if (response.results !== undefined) {
                    if (response.results.length > 0) {
                        let most = response.results[0]
                        let {address_components, formatted_address, place_id} = most
                        this.setState({address: address_components, textadress: formatted_address, place: place_id})

                        let results = response.results;
                        let shortcountry;
                        let mcountry;
                        for (let i = 0; i < results[0].address_components.length; i++) {
                            for (let j = 0; j < results[0].address_components[i].types.length; j++) {
                                if (results[0].address_components[i].types[j] === "country") {
                                    mcountry = results[0].address_components[i];
                                    shortcountry = mcountry.short_name;
                                    this.setState({shortCountry: mcountry.short_name, longCountry: mcountry.long_name})
                                } else if (results[0].address_components[i].types[j] === "locality") {
                                    const name = results[0].address_components[i].short_name;
                                    this.setState({townName: name});
                                    getTownInformationName(name).then((result) => {
                                        let town = null;
                                        if (result instanceof Array) {
                                            town = result[0];
                                        } else
                                            town = result;
                                        this.setState({town: town});
                                    })
                                }
                            }
                        }
                        getListCountriesActive().then((cnt) => {
                            this.setState({countries: cnt})
                            console.debug(cnt, shortcountry);
                            var found = false
                            for (let i of cnt) {
                                if (i.code_country === shortcountry) {
                                    found = true
                                    this.setState({indicatif: i.code_dial, country: i.name})
                                    this.getNetworks(i.code_dial);
                                }
                            }
                            if (!found) {
                                Alert.alert("Impossible de recupérer vos informations", "Nous n'avons pas pu recuperer les informations de votre pays veuillez contacter les administrateurs", [{text: "OK"}]);

                            }
                        })


                    }

                }
            }).catch((e) => {
                this.showErrorDialog()
            });
            this.setState({myPosition: myPosition});
            if (this.mapRef !== undefined && this.mapRef !== null) {
                this.mapRef.animateToCoordinate({
                    latitude: myPosition.latitude,
                    longitude: myPosition.longitude
                }, 1000);
                this.mapRef.animateToRegion({
                    latitude: myPosition.latitude,
                    longitude: myPosition.longitude,
                    latitudeDelta: 0.03,
                    longitudeDelta: 0.01,
                }, 1000)
            }
        }

    }

    componentWillUnmount() {
        this.mounted = false;
        // eslint-disable-next-line no-undef
        if (this.watchID) Geolocation.clearWatch(this.watchID);
    }

    renderUserGeoAccount() {

        return (
            <View style={styles.container}>
                {this.prepareModal()}
                <View style={{flexDirection: 'row'}}>
                    <Icon.Button name={"keyboard-backspace"}
                                 color={"white"}
                                 size={24}
                                 backgroundColor={theme.primary}
                                 onPress={() => this.props.navigation.pop()}
                    />
                    <Text style={styles.bigtitle}>{I18n.t('LAST_STEP')}</Text>

                </View>
                <ScrollView style={styles.container}>
                    <View
                        style={{
                            width: responsiveWidth(90),
                            marginTop: 20,
                            alignSelf: 'center',
                            borderRadius: 10,
                            paddingLeft: 20,
                            paddingRight: 20,
                            backgroundColor: 'white'
                        }}>
                        <Dropdown
                            label={I18n.t('COUNTRY_CHOICE')}
                            data={this.state.countries}
                            useNativeDriver={true}
                            disabled={this.state.disableNetwork}

                            value={this.state.country === null ? "" :
                                this.state.country}
                            onChangeText={(value, index, data) => {
                                this.setState({country: value, indicatif: value.code_dial, network: null})
                                this.getNetworks(value.code_dial)
                            }}
                            valueExtractor={(value) => {
                                return value.name
                            }}
                            labelExtractor={(value) => {
                                return value.name
                            }}
                        />
                    </View>
                    <Animatable.View ref={(comp) => {
                        this.numanim = comp
                    }}>
                        <View style={{flexDirection: 'row', flex: 1}}>
                            <Fumi iconClass={FontAwesomeIcon} iconName={'flag'}
                                  value={this.state.indicatif}
                                  enabled={false}
                                  editable={false}
                                  onChangeText={(text) => {
                                      let phonenum = text + this.state.contact !== undefined ? this.state.contact : "";
                                      this.setState({indicatif: text, phone: phonenum})
                                  }}
                                  style={{
                                      width: responsiveWidth(30),
                                      height: responsiveHeight(10),
                                      alignSelf: 'center',
                                      marginTop: responsiveHeight(2),
                                      marginLeft: responsiveWidth(5),
                                      marginRight: responsiveWidth(5),
                                      borderRadius: 5,
                                  }}
                            />
                            <View>
                                <Fumi iconClass={FontAwesomeIcon} iconName={'phone'}
                                      placeholder={I18n.t('PHONE')}
                                      iconColor={'#f95a25'}
                                      ref={(comp) => {
                                          this.num_input = comp
                                      }}
                                      iconSize={20}
                                      onChangeText={(text) => {
                                          let phonenumber = text
                                          this.setState({phone: phonenumber, contact: text})
                                      }}
                                      style={{

                                          marginTop: responsiveHeight(2),
                                          marginRight: responsiveWidth(5),

                                          width: responsiveWidth(55),
                                          borderRadius: 5,
                                      }}
                                >
                                </Fumi>
                                <Fumi iconClass={FontAwesomeIcon} iconName={'phone'}
                                      placeholder={I18n.t('PHONE_TRANSACTION')}
                                      iconColor={'#f95a25'}
                                      ref={(comp) => {
                                          this.num_input = comp
                                      }}
                                      iconSize={20}
                                      onChangeText={(text) => {
                                          let phonenumber = text
                                          this.setState({phoneTransaction: phonenumber, contactTransaction: text})
                                      }}
                                      style={{

                                          marginTop: responsiveHeight(2),
                                          marginRight: responsiveWidth(5),

                                          width: responsiveWidth(55),
                                          borderRadius: 5,
                                      }}
                                >
                                </Fumi>
                            </View>
                        </View>
                    </Animatable.View>

                    <Animatable.View ref={(comp) => {
                        this.networkanim = comp
                    }}>
                        <View
                            style={{
                                width: responsiveWidth(90),
                                marginTop: 20,
                                alignSelf: 'center',
                                borderRadius: 10,
                                paddingLeft: 20,
                                paddingRight: 20,
                                backgroundColor: 'white'
                            }}

                        >
                            <Button
                                style={{borderColor: 'transparent'}}
                                isDisabled={this.state.disableNetwork}
                                onPress={() => {
                                    this.setState({networksinglePickerVisible: true})
                                }}>
                                <View>
                                    <Text style={material.subheading}>{this.state.select_network}</Text>
                                    <Text
                                        style={material.subheading}>{this.state.network ? this.state.network.name : ""}</Text>
                                </View>
                            </Button>

                        </View>
                    </Animatable.View>


                    {this.state.provider_classes.length >= 1 && <View
                        style={{
                            width: responsiveWidth(90),
                            marginTop: 20,
                            alignSelf: 'center',
                            borderRadius: 10,
                            paddingLeft: 20,
                            paddingRight: 20,
                            backgroundColor: 'white'
                        }}>
                        <Dropdown
                            label={I18n.t('CLASSE_PRESTATAIRE')}
                            data={this.state.provider_classes}
                            useNativeDriver={true}
                            value={this.state.provider_class === null ? "" :
                                this.state.provider_class}
                            onChangeText={(value, index, data) => {
                                console.log("Value", value);
                                this.setState({provider_class: value});
                            }}
                            valueExtractor={(value) => {
                                return value
                            }}
                            labelExtractor={(value) => {
                                return value.name
                            }}
                        />
                    </View>}

                    <Text
                        style={{
                            fontSize: 16,
                            marginTop: 10,
                            marginLeft: responsiveWidth(6),
                            marginRight: responsiveWidth(6),
                            color: 'white',
                            fontWeight: 'bold'
                        }}
                    >{I18n.t('WAIT_LOADING_POSITION')}</Text>
                    <Animatable.View
                        ref={(comp) => {
                            this.mapanim = comp
                        }}
                    >
                        <MapView
                            liteMode
                            ref={(ref) => {
                                this.mapRef = ref
                            }}
                            style={styles.map}
                        >
                            {this.state.myPosition !== undefined ?
                                <Marker
                                    title={I18n.t('YOUR_THERE')}
                                    minZoomLevel={18}
                                    coordinate={{
                                        longitude: this.state.myPosition.longitude,
                                        latitude: this.state.myPosition.latitude
                                    }}
                                /> :
                                null}
                        </MapView>
                    </Animatable.View>
                    <TouchableOpacity style={{flexDirection: 'row', alignItems: 'center'}}>
                        <Image

                            style={{
                                width: 24, height: 24,
                                marginLeft: responsiveWidth(6)
                            }}
                            source={require('./../../datas/img/userplace.png')}
                        />
                        <Text
                            style={{
                                fontSize: 16,
                                marginTop: 10, marginRight: responsiveWidth(6), color: 'white', fontWeight: 'bold'
                            }}
                        >{this.state.textadress !== undefined ? this.state.textadress : I18n.t('TAKE_MY_POSITION')}</Text>
                    </TouchableOpacity>
                    <Button style={styles.btnvalide} textStyle={styles.textbtnvalide}
                            isLoading={this.state.isLoading}
                            onPress={() => {
                                console.log(this.state);
                                this.checkUserGeolocated()
                            }}>{I18n.t('CREATE_ACCOUNT')}</Button>


                </ScrollView>
                <MaterialDialog
                    title={'Selecionner un reseau'}
                    items={LONG_LIST.map((row, index) => ({value: row, label: row}))}
                    visible={this.state.networksinglePickerVisible}
                    selectedItem={this.state.singlePickerSelectedItem}
                    onCancel={() => this.setState({networksinglePickerVisible: false})}
                    onOk={result => {
                        this.setState({networksinglePickerVisible: false});
                        this.setState({singlePickerSelectedItem: result.selectedItem});
                    }}
                >
                    <FlatList style={{height: responsiveHeight(40)}}
                              data={this.state.networks}
                              renderItem={({item}) => this.renderRow(item)}/>
                </MaterialDialog>
            </View>
        )

    }

    onRowPress(rowID) {
        this.setState({network: rowID})
    }

    renderRow = (row) => (
        <TouchableOpacity key={row} onPress={() => this.onRowPress(row)}>
            <View style={styles.rowContainer}>
                <View style={styles.iconContainer}>
                    <Icon
                        name={this.state.network && row.name === this.state.network.name ? 'radio-button-checked' : 'radio-button-unchecked'}
                        color={this.state.network && row.name === this.state.network.name ? theme.accent : this.props.colorAccent}
                        size={24}
                    />
                </View>
                <Text style={material.subheading}>{row.name}</Text>
            </View>
        </TouchableOpacity>
    );

    renderUserAccount() {
        return (<ScrollView style={styles.container}>
            {this.prepareModal()}
            <View style={{flexDirection: 'row'}}>
                <Icon.Button name={"keyboard-backspace"}
                             color={"white"}
                             size={24}
                             backgroundColor={theme.primary}
                             onPress={() => this.props.navigation.pop()}
                />
                <Text style={styles.bigtitle}>{I18n.t('LAST_STEP')}</Text>

            </View>
            <View
                style={{
                    width: responsiveWidth(90),
                    marginTop: 20,
                    alignSelf: 'center',
                    borderRadius: 10,
                    paddingLeft: 20,
                    paddingRight: 20,
                    backgroundColor: 'white'
                }}

            >
                <Dropdown
                    label={I18n.t('COUNTRY_CHOICE')}
                    data={this.state.countries}
                    useNativeDriver={true}
                    value={this.state.country === null ? "" :
                        this.state.country}
                    onChangeText={(value, index, data) => {
                        this.setState({country: value, indicatif: value.code_dial, network: null})

                        this.getNetworks(value.code_dial)
                    }}
                    valueExtractor={(value) => {
                        return value
                    }}
                    labelExtractor={(value) => {
                        return value.name
                    }}
                />
            </View>
            <Animatable.View ref={(comp) => {
                this.numanim = comp
            }}>
                <View style={{flexDirection: 'row', flex: 1}}>
                    <Fumi iconClass={FontAwesomeIcon} iconName={'flag'}
                          value={this.state.indicatif}
                          editable={false}

                          onChangeText={(text) => {

                              this.setState({indicatif: text})
                          }}
                          style={{
                              width: responsiveWidth(30),
                              marginTop: responsiveHeight(2),
                              marginLeft: responsiveWidth(5),
                              marginRight: responsiveWidth(5),
                              borderRadius: 5,
                          }}
                    />
                    <Fumi iconClass={FontAwesomeIcon} iconName={'phone'}
                          label={I18n.t('PHONE_NUMBER')}
                          iconColor={'#f95a25'}
                          ref={(comp) => {
                              this.num_input = comp
                          }}
                          iconSize={20}
                          onChangeText={(text) => {
                              let phonenumber = text
                              this.setState({phone: phonenumber})
                          }}
                          style={{

                              marginTop: responsiveHeight(2),
                              marginRight: responsiveWidth(5),

                              width: responsiveWidth(55),
                              borderRadius: 5,
                          }}
                    >
                    </Fumi>
                </View>
            </Animatable.View>

            <Animatable.View ref={(comp) => {
                this.networkanim = comp
            }}>
                <View
                    style={{
                        width: responsiveWidth(90),
                        marginTop: 20,
                        alignSelf: 'center',
                        borderRadius: 10,
                        paddingLeft: 20,
                        paddingRight: 20,
                        backgroundColor: 'white'
                    }}

                >
                    <Dropdown
                        label={I18n.t('NETWORK_CHOICE')}
                        data={this.state.networks}
                        value={this.state.network == null ? "" : this.state.network}
                        onChangeText={(value, index, data) => {
                            this.setState({network: value})
                        }}
                        valueExtractor={(value) => {
                            return value
                        }}
                        labelExtractor={(value) => {
                            return value.name
                        }}
                    />
                </View>
            </Animatable.View>
            <Button style={styles.btnvalide} textStyle={styles.textbtnvalide}
                    isLoading={this.state.isLoading}
                    onPress={() => {
                        this._onUserCreateAccount()
                    }}>{I18n.t('CREATE_ACCOUNT')}</Button>

        </ScrollView>)

    }

    _onUserCreateAccount() {
        let {myPosition, textaddress, place, user, network, phone, indicatif} = this.state;
        this.setState({isLoading: true})
        if (user !== undefined) {
            if (this.checkOrShake(myPosition, this.mapanim)) {
                if (this.checkOrShake(phone, this.numanim)) {
                    if (this.checkOrShake(network, this.networkanim)) {
                        var data = {};
                        data.tag = "member"
                        data['type'] = "create_user"
                        data['phone'] = indicatif + phone;
                        data['network'] = network;
                        data['town'] = this.state.town;
                        data['latitude'] = myPosition.latitude;
                        data['longitude'] = myPosition.longitude;
                        for (let i in user) {
                            data[i] = user[i];
                        }
                        //console.log(data);
                        createUserAccount(data).then((result) => {
                            console.log("result", result)
                            if (result.success !== undefined && result.success === 1) {
                                Alert.alert(I18n.t("CONNEXION_SUCCESSFUL"),
                                    I18n.t('ACCOUNT_CREATED_SUCCESS')
                                    , [{
                                        text: 'OK', onPress: () => {
                                            this.props.navigation.popToTop()
                                            this.setState({isLoading: false})
                                        }
                                    }], {cancelable: false})
                            } else {
                                if (result.error !== undefined) {
                                    switch (result.error) {
                                        case -3:
                                            Alert.alert(I18n.t("CONNEXION_SUCCESSFUL"), I18n.t('FAILED_TEXT_CONTACT_ADMIN')
                                                , [{text: 'OK', onPress: () => ""}], {cancelable: false})
                                            break;
                                        default:
                                            Alert.alert(I18n.t("CONNEXION_SUCCESSFUL"), result.error_msg
                                                , [{text: 'OK', onPress: () => ""}], {cancelable: false})
                                    }
                                    this.setState({isLoading: false})
                                }
                            }
                        }).catch((error) => {
                            this.setState({isLoading: false})
                        })

                    } else this.setState({isLoading: false})
                } else this.setState({isLoading: false})
            } else this.setState({isLoading: false})
        } else {
            this.setState({isLoading: false})

        }
    }

    checkUserGeolocated() {
        let {myPosition, textaddress, place, indicatif, user, network, phone, phoneTransaction} = this.state;
        this.setState({isLoading: true})
        console.log(this.state);
        if (user !== undefined) {
            if (this.checkOrShake(myPosition, this.mapanim)) {
                if (this.checkOrShake(phone, this.numanim)) {
                    if (this.checkOrShake(network, this.networkanim)) {
                        var data = {};
                        data.tag = "member";
                        data.type = "create_geolocated_user";
                        data['phone'] = indicatif + phone;
                        data['phone_transaction'] = indicatif + phoneTransaction;

                        if (this.state.provider_class !== null)
                            data['provider_class_id'] = this.state.provider_class.id;

                        data['network'] = network;
                        data['town'] = this.state.town;
                        data['latitude'] = myPosition.latitude;
                        data['longitude'] = myPosition.longitude;
                        for (let i in user) {
                            data[i] = user[i];
                        }
                        data['category'] = user.category;

                        data['active'] = '0';
                        createGeolocatedAccount(data).then((result) => {
                            console.log(result);
                            if (result.success !== undefined && result.success === 1) {
                                const message = result.category === 'super' ? I18n.t("HYPERVISOR_MUST_VALIDATE_SUPERVISOR")
                                    : I18n.t("ACCOUNT_SUCCESSFULL_CREATED")
                                Alert.alert("", message, [{
                                    text: "Ok",
                                    onPress: () => {
                                        this.props.navigation.popToTop()
                                    }
                                }])
                                setTimeout(() => {
                                    this.setState({isLoading: false})

                                }, 1000)
                                this.props.navigator.push({
                                    screen: route.login
                                })
                                this.setState({isLoading: false})
                            } else {

                                /* Crashlytics.log(JSON.stringify({"type":"erreur lors de la creation","data":result}))
                                 Answers.logCustom("error",JSON.stringify(result))*/
                                console.warn(result)
                                if (result.error !== undefined) {
                                    switch (result.error) {
                                        case -3:
                                            Alert.alert("", I18n.t('UNABLE_TO_CREATE_ACCOUNT'), [{
                                                text: "Ok",
                                                onPress: () => {
                                                }
                                            }])
                                            break;
                                        default:
                                            if (result.error_msg)
                                                Alert.alert("", result.error_msg, [{
                                                    text: "Ok",
                                                    onPress: () => {
                                                    }
                                                }])
                                            else if (result.sql_error)
                                                Alert.alert(I18n.t('UNABLE_TO_CREATE_ACCOUNT'), result.sql_error, [{
                                                    text: "Ok",
                                                    onPress: () => {
                                                    }
                                                }])
                                    }
                                    this.setState({isLoading: false})
                                }
                            }
                        }).catch((error) => {
                            this.setState({isLoading: false})
                        })

                    } else this.setState({isLoading: false})
                } else this.setState({isLoading: false})
            } else this.setState({isLoading: false})
        } else {
            this.setState({isLoading: false})

        }
    }

    checkOrShake(champ, view) {
        let res = false;
        if (champ !== undefined && champ.length > 0) {
            res = true;
        } else if (champ !== Array && champ !== undefined) {
            res = true
        } else {
            view.shake(800)
        }
        return res;
    }

    prepareModal() {
        return (<MaterialDialog
            visible={this.state.modalVisible}
            title={I18n.t("LOADING_INFO")}
        >
            <View style={{justifyContent: 'center', alignItems: 'center'}}>
                <Text>{I18n.t("LOADING_DESCRIPTION_COUNTRY")}</Text>
                <ProgressBarAndroid/>
            </View>
        </MaterialDialog>)
    }
}
const SHORT_LIST = ['List element 1', 'List element 2', 'List element 3'];

const LONG_LIST = [
    'List element 1',
    'List element 2',

    'List element 5',
    'List element 6',
    'List element 7',
    'List element 8',
    ,
];

const styles = StyleSheet.create({
    rowContainer: {
        height: 52,
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },
    iconContainer: {
        marginRight: 16,
    },
    container: {
        flex: 1,
        backgroundColor: theme.primary,
    },
    textbtnvalide: {
        color: 'white',
        fontWeight: 'bold'
    },
    bigtitle: {
        color: 'white',
        fontSize: 20,
        flex: 1,
        fontWeight: 'bold',
        textAlign: 'center',
        margin: 20,
    },
    subbigtitle: {
        color: 'white',
        fontSize: 17,
        textAlign: 'center',
        margin: 5,
    },
    map: {
        height: 200,
        marginRight: responsiveWidth(5),
        marginLeft: responsiveWidth(5),
        marginVertical: 10,
    },
    btnvalide: {
        marginTop: 20,
        marginLeft: 20,
        marginRight: 20,
        borderColor: 'transparent',
        backgroundColor: theme.accentLight,
        height: 52
    },
    input: {
        height: 60,
        marginTop: responsiveHeight(2),
        marginLeft: responsiveWidth(5),
        marginRight: responsiveWidth(5),
        borderRadius: 5,
    }
})
