import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, Animated, BackHandler, TouchableOpacity, PermissionsAndroid, Platform, ProgressBarAndroid, ScrollView, Alert, StatusBar, AsyncStorage } from 'react-native'; import PropTypes from 'prop-types'; import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'; import { responsiveHeight,responsiveWidth,responsiveFontSize } from 'react-native-responsive-dimensions'; import { Sae } from 'react-native-textinput-effects'; import Button from 'apsl-react-native-button'; let theme=require('./../../../utils/theme.json'); import {login,saveNewuser,getCountryNetwork} from './../../../webservice/AuthApi'; import * as Animatable from 'react-native-animatable'; import isEqual from 'lodash/isEqual' import {getPositionInformation} from './../../../webservice/MapService' import SwitchSelector from 'react-native-switch-selector' import I18n from 'react-native-i18n' let route=require('./../../../route.json'); require('./../../../utils/Translations') let country=require('./../../../utils/country_code.json'); import {IlinkEmitter} from './../../../utils/events' import {readUser} from "../../../webservice/AuthApi"; import {MaterialDialog} from "react-native-material-dialog" import Spinner from "react-native-loading-spinner-overlay" import Geolocation from "react-native-geolocation-service" const GEOLOCATION_OPTIONS= { enableHighAccuracy: true, timeout: 20000 } const 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 widthButton=responsiveWidth(80)>350?350:responsiveWidth(80) export class LoginUi extends Component{ handlePhoneRef=ref=>this.phoneRef=ref; handlePasswordRef=ref=>this.passRef=ref; static defaultProps = { enableHack: false, geolocationOptions: null, }; async requestCameraPermission() { if(Platform.OS === "android"){ 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({loadingDialog:false}) Alert.alert(I18n.t("TITLE_UNABLE_TO_AUTORISE"), I18n.t("MISSING_AUTORISATION_LOCATION"), [{text:I18n.t("RESTART"),onPress:()=>{ this.requestCameraPermission() }},{text:I18n.t("QUIT_"),onPress:()=>{ BackHandler.exitApp() }}], {cancelable:false} ) } } catch (err) { console.warn(err) this.setState({loadingDialog:false}) Alert.alert(I18n.t("TITLE_ERROR_SURVENU"), I18n.t("TEXT_ERROR_START_APPLICATION"), [{text:I18n.t("RESTART"),onPress:()=>{ this.requestCameraPermission() }},{text:I18n.t("QUIT_"),onPress:()=>{ // BackHandler.exitApp() }}], {cancelable:false} ) } }else{ this.watchLocation() } } showConnexionAlertError(){ this.setState({loadingDialog:false}) Alert.alert(I18n.t("TITLE_PROBLE_COME"), I18n.t("TEXT_UNABLE_TO_GET_YOUR_POSITION"), [{text:I18n.t("QUIT_"),onPress:()=>{ BackHandler.exitApp()}},{text:I18n.t("RESTART"), onPress:()=>{ this.setState({loadingDialog:true}) this.watchLocation()}}], {cancelable:false} ) } _storeData = async (position) => { try { console.warn("save result",await AsyncStorage.setItem('position', JSON.stringify(position))); } catch (error) { console.warn("store error",error) } }; _retrieveData = async () => { try { const value = await AsyncStorage.getItem('position'); if (value !== null) { let re=JSON.parse(value) re.longitudeDelta=0.04 re.latitudeDelta=0.01 const pos=JSON.parse(value) this.setState({region:re,oldPosition:pos}) } } catch (error) { console.warn(error) } }; watchLocation(geo=null) { const options= geo==null?GEOLOCATION_OPTIONS:geo this.watchID = Geolocation.getCurrentPosition((position) => { const myLastPosition = this.state.myPosition; const myPosition = position.coords; if (!isEqual(myPosition, myLastPosition)) { console.warn(myPosition) if(myPosition.longitude!==0 && myPosition.latitude!==0) { this._storeData(myPosition) this.retreiveinformationFromPosition(myPosition) }else{ if(!this.state.alreadyRetry) { this.setState({alreadyRetry: true}) let geo = {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000} this.watchLocation(geo) }else{ if(this.state.oldPosition){ this.retreiveinformationFromPosition(this.state.oldPosition) }else{ Geolocation.watchPosition((position)=>{ if(position.longitude!==0 && position.latitude!==0) { this._storeData(position) this.retreiveinformationFromPosition(position) }else{ Alert.alert(I18n.t("UNABLE_GET_INFORMATION") ,I18n.t('UNABLE_GET_INFORMATION_TEXT'), [{text:I18n.t("EXIT"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("RESTART"),onPress:()=>{this.watchLocation()}}], {cancelable:false} )}},(error)=>{ this.setState({loadingDialog:false}) Alert.alert(I18n.t("TITLE_ERROR_SURVENU"), I18n.t("TEXT_ERROR_START_APPLICATION"), [{text:"Ok",onPress:()=>{ BackHandler.exitApp() }}], {cancelable:false}) },GEOLOCATION_OPTIONS) } } } } },(positionError) => { console.warn(positionError) Alert.alert(I18n.t("UNABLE_GET_INFORMATION") ,I18n.t('UNABLE_GET_INFORMATION_TEXT'), [{text:I18n.t("EXIT"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("RESTART"),onPress:()=>{this.watchLocation()}}], {cancelable:false} ) } ,options) } retreiveinformationFromPosition(myPosition){ getPositionInformation(myPosition).then((response)=>{ console.log(response,myPosition) 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}) this.getNetworks(mcountry.long_name) } } } for (let i of country) { if(i.code=== shortcountry){ this.setState({indicatif:i.dial_code,enterPhone:i.dial_code})}} }else{ } this.setState({phoneEnabled:true,loadingDialog:false}); }else{ console.log(myPosition,response) this.showConnexionAlertError() } }).catch((e)=>{ this.setState({phoneEnabled:true,loadingDialog:false}); Alert.alert(I18n.t("TITLE_PROBLE_COME"), I18n.t("TEXT_UNABLE_TO_GET_COUNTRY_INFO"),[{text:I18n.t("NO"),onPress:()=>{ BackHandler.exitApp() }},{text:I18n.t("YES"),onPress:()=>{ this.watchLocation() }}],{cancelable:false}) }); } componentDidMount(){ this._retrieveData() this.requestCameraPermission() } componentWillUnmount(){ if(this.focusListener) this.focusListener.remove() } getNetworks(pays) { if (pays){ getCountryNetwork(pays).then((result) => { this.reseaux = []; let networks = result[0]; for(let prop in networks){ if(networks[prop]!=="" && networks[prop].toLowerCase()!==pays.toLowerCase()){ this.reseaux.push(networks[prop]); } } this.setState({networks:this.reseaux}); }, (err) => { console.log(err); }); } else { let msg = "impossible de récupérer le nom du pays"; } } constructor(props){ super(props); this.state=this.initState(); this.Animation=new Animated.Value(0); this.BackgroundColorConfig=this.Animation.interpolate( { inputRange: [ 0,0.5, 1 ], outputRange: this.state.colorsscheme }); this.BackgroundColorConfigAdmin=this.Animation.interpolate( { inputRange: [0, 0.5, 1], outputRange: this.state.colorsscheme.reverse() }) } StartBackgroundColorAnimation = (value) => { this.Animation.setValue(value===0?0:1); this.setState({stateLogin:value,typeaccount:value}) Animated.timing( this.Animation, { toValueF: value===1?0:1, duration: 500 } ).start(); } async gotoHome(){ IlinkEmitter.emit("userconnect") let readU=await readUser() let road=""; if(!readU.category) road="App" else { switch (readU.category) { case 'geolocated': road="AgentApp" break; case 'super': road="adminApp" break default: road="supAdminApp" } } this.props.navigation.navigate(road) } gotoTypeCreated(){ this.props.navigation.push(route.typeaccountcreate, { type: this.state.typeaccount, }); } initState(){ return { password:"", typeaccount:0, enterPhone:"", isLoging:false, phoneEnabled:false, snackVisible:false, snackText:'', loadingDialog:true, stateLogin:-1, colorsscheme: [ theme.primary,theme.primaryDark,theme.primaryDarkAdvanced ] } } options=[ { label: I18n.t('USER'), value: 0}, { label: I18n.t('AGENT'), value: 1}, ] BackgroundColorConfig:null BackgroundColorConfigAdmin:null render(){ return ( { this.props.navigation.push(route.helpmenu) }} > {I18n.t('HELP_')} {this.numberRef=com}} onChangeText={(text)=>this.setState({enterPhone:text})} labelStyle={style.labelInput} /> {this._pass=component}} iconClass={FontAwesomeIcon} iconName={'lock'} style={style.input} iconColor={'white'} labelStyle={style.labelInput} autoCapitalize={'none'} secureTextEntry={true} onChangeText={(text)=>this.setState({password:text})} autoCorrect={false} /> { this.gotoForgottenPass() }}> {I18n.t("FORGOTTEN_PASSWORD")} { this.StartBackgroundColorAnimation(value) }} /> {I18n.t("OR_BIG")} )} gotoForgottenPass() { this.props.navigation.push(route.forgotpass,{ type: this.state.typeaccount, }) } connectClicked() { if(this.state.password===null || this.state.password===undefined ||this.state.password.length<3 || this.state.password.lenght<3){ this.passRef.shake(800) } else { this.setState(previousState => { return {isLoging: !previousState.isLoging}; }) login(this.state.enterPhone, this.state.password, this.state.typeaccount).then((responseJson) => { console.warn(responseJson) if (responseJson.success === 1) { this.setState(previousState => { return {isLoging: !previousState.isLoging}; }) const user = responseJson; if(!user.error){ if (user.etat === "1" || user.etat === 1) { saveNewuser(user); this.setState({user:user}) Alert.alert( I18n.t("CONNEXION_SUCCESSFUL"), I18n.t("CONNEXION_SUCCESSFULL_TEXT"), [ {text:'Ok',onPress:()=>{ this.setState(previousState => { return {isLoging: !previousState.isLoging}; }) this.gotoHome() }} ], {cancelable:false} ) } else { if (user.category !== 'super') { this.props.navigation.push(route.activateaccount,{type: this.state.typeaccount, user: user}) } else { if (user.etat_demande === 0 || user.etat_demande==='0') { Alert.alert( I18n.t('DONT_VALIDATE_ACCOUNT'), I18n.t('UNVALIDATE_ACCOUNT_TEXT'), [ {text:'Ok',onPress:()=>{}} ], {cancelable:false} ) } else { this.props.navigation.push(route.activateaccount,{type: this.state.typeaccount, user: user}) } } } }else{ this.setState(previousState => { return {isLoging: !previousState.isLoging}; }) Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{this.connectClicked()}} ], {cancelable:false} ) } } else if (responseJson === null) { this.setState(previousState => { return {isLoging: !previousState.isLoging}; }) } else { console.log(responseJson) let message = ''; switch (responseJson.error) { case 1: this.phoneRef.shake(1200); this.passRef.shake(1200); message = I18n.t("UNABLE_TO_CONNECT") break; case -1: this.phoneRef.shake(1200); message =I18n.t('WRONG_PHONE_NUMBER') break; case -2: message=I18n.t('WRONG_PHONE_NUMBER'); this.phoneRef.shake(1200); break; case -3: message=I18n.t("WRONG_PASSWORD") this.passRef.shake(1200); break; default: this.passRef.shake(1200); message = null break; } if(message===null) { Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ { text: I18n.t("NO"), onPress: () => { BackHandler.exitApp() } }, { text: I18n.t("YES"), onPress: () => { this.connectClicked() } } ], {cancelable: false} ) }else { Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), message , [ { text:"OK", onPress: () => { } } ], {cancelable: false} ) this.setState(previousState => { return { isLoging: !previousState.isLoging, snackVisible: true, snackText: message }; }) setTimeout(() => { this.setState({snackVisible: false}) }, 2000) } } }) .catch((e)=>{ this.setState(previousState => { return {isLoging: !previousState.isLoging}; }) Alert.alert( I18n.t("UNABLE_TO_CONNECT_TITLE"), I18n.t('TEXT_NETWORK_UNABLE') , [ {text:I18n.t("NO"),onPress:()=>{BackHandler.exitApp()}}, {text:I18n.t("YES"),onPress:()=>{this.connectClicked()}} ], {cancelable:false} ) }) } } } const separator=StyleSheet.create({ line:{ height:1.5, flex:1, backgroundColor:'white', marginLeft:30, marginRight:30 }, text:{ color:'white', fontWeight:'bold', }, container:{ flexDirection:'row', alignItems:'center' }, btnContainer:{ flexDirection:'column', justifyContent:'center', }, }) const style=StyleSheet.create({ container:{ flex:1, justifyContent:"center" }, switch:{ margin:15, }, contentSwitch:{ width:responsiveWidth(70), alignItems:'center', alignSelf:"center", marginTop:10, marginLeft:10 }, lostpassword:{ color:'white', alignSelf:'flex-end', marginTop:60, fontWeight:'bold', marginRight:20 }, logoContaner:{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, logo:{ width:responsiveWidth(90), resizeMode:"contain" }, title:{ fontSize:responsiveFontSize(4), alignSelf: 'center', fontWeight:'bold', color:'white', }, loginBtnText:{ color:theme.primary, fontWeight:'bold', fontSize:15 }, loginBtnText2:{ color:"white", fontWeight:'bold', fontSize:15 }, loginBtn:{ width:widthButton, height:48, alignSelf: 'center', marginTop:20, borderRadius:responsiveHeight(4), backgroundColor:'white', borderColor:'transparent', }, loginBtn1:{ width:widthButton, marginTop: responsiveHeight(2), height:48, alignSelf: 'center', borderRadius:responsiveHeight(4), backgroundColor:theme.accentLight, borderColor:'transparent', }, input:{ width:responsiveWidth(70), alignSelf: 'center', marginTop: 5, }, labelInput:{ color:"white", fontWeight: 'normal', } })