import Button from 'apsl-react-native-button';
import React, {Component} from 'react';
import {
Alert,
Image,
PermissionsAndroid,
Platform,
ProgressBarAndroid,
ScrollView,
StyleSheet,
Text,
View
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Dialog from "react-native-dialog";
import {TouchableOpacity} from 'react-native-gesture-handler';
import I18n from 'react-native-i18n';
import ImagePicker from 'react-native-image-crop-picker';
import {responsiveHeight, responsiveWidth} from 'react-native-responsive-dimensions';
import {Fumi} from 'react-native-textinput-effects';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {Color} from '../../config/Color';
import isNil from 'lodash/isNil';
import isEqual from 'lodash/isEqual';
import {MaterialDialog} from "react-native-material-dialog";
import {getListCountriesActive, getTownInformationName, readUser} from './../../webservice/AuthApi';
import {FontWeight, Typography} from '../../config/typography';
import {connect} from 'react-redux';
import Geolocation from 'react-native-geolocation-service';
import {bindActionCreators} from 'redux';
import {ProgressDialog} from 'react-native-simple-dialogs';
import {
getUserIdentificationAction,
getUserIdentificationResetAction,
validateIdentificationAction,
validateIdentificationResetAction
} from '../../webservice/IdentificationApi'
import {getPositionInformation} from '../../webservice/MapService';
let theme = require('./../../utils/theme.json');
let route = require('./../../route.json');
const GEOLOCATION_OPTIONS = { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, useSignificantChanges: true };
const moment = require('moment');
class ValidateIdentification extends Component {
static navigatorStyle = {
navBarBackgroundColor: Color.primaryColor,
statusBarColor: Color.primaryDarkColor,
navBarTextColor: '#FFFFFF',
navBarButtonColor: '#FFFFFF'
};
static navigationOptions = () => {
return {
drawerLabel: () => null,
headerTitle: I18n.t('VALIDATE_IDENTIFICATION_DESCRIPTION'),
headerTintColor: 'white',
headerStyle: {
backgroundColor: Color.primaryColor,
marginTop: 0,
color: 'white'
},
headerTitleStyle: {
color: "white"
},
title: I18n.t('VALIDATE_IDENTIFICATION_DESCRIPTION'),
}
};
constructor(props) {
super(props);
this.state = {
numeroTelephone: null,
image: null,
displayImage: false,
idNetwork: null,
idUser: null,
idIdentification: null,
displayUploadButtons: false,
triggerSubmitClick: false,
triggerValidateClick: false,
isIdentified: false,
modalVisible: true,
isIdentifiedValidated: false,
userId: null,
isLoging: false,
countries: [],
town: [],
townName: null,
country: null,
datatoSend: null
};
this.dataToSendTemp = new FormData();
this.props.getUserIdentificationResetAction();
this.props.validateIdentificationResetAction();
}
componentDidMount() {
readUser().then((user) => {
if (user) {
if (user !== undefined) {
this.setState({ user });
}
}
});
if (Platform.OS === 'android') {
this.requestCameraPermission();
} else {
this.watchLocation();
}
}
componentWillUnmount() {
this.mounted = false;
if (this.watchID) Geolocation.clearWatch(this.watchID);
}
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() } }])
}
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)
}
}
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()
}
}])
}
}
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;
getTownInformationName(name).then((result) => {
let town = null;
if (result instanceof Array) {
town = result[0];
} else {
town = result;
}
this.setState({ modalVisible: false });
})
}
}
}
getListCountriesActive().then((cnt) => {
this.setState({ countries: cnt })
var found = false
for (let i of cnt) {
if (i.code_country === shortcountry) {
found = true;
this.setState({ modalVisible: false, 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)
} */
}
}
createFormData = (key, photo) => {
this.dataToSendTemp.append(key, {
name: photo.path.split('/').pop(),
type: photo.mime,
uri:
Platform.OS === "android" ? photo.path : photo.path.replace("file://", "")
});
};
renderLoader = () => {
return (
, nextContext: any) {
const { resultValidateIdentification, errorValidateIdentification } = nextProps;
if (resultValidateIdentification !== null) {
if (typeof resultValidateIdentification.response !== 'undefined') {
if (resultValidateIdentification.status === 200) {
Alert.alert(
I18n.t('VALIDATION_EFFECTUE'),
I18n.t('USER_SUCCESSFULLY_VALIDATED'),
[
{
text: I18n.t("OK"), onPress: () => {
this.props.validateIdentificationResetAction();
this.setState({ triggerSubmitClick: false });
this.props.navigation.pop();
}
}
],
{ cancelable: false }
)
}
}
}
if (errorValidateIdentification !== null) {
if (typeof errorValidateIdentification.data !== 'undefined') {
Alert.alert(
I18n.t('ERROR_LABEL'),
errorValidateIdentification.data.error,
[
{
text: I18n.t("OK"), onPress: () => {
this.props.validateIdentificationResetAction();
this.setState({ triggerSubmitClick: false });
}
}
],
{ cancelable: false }
)
} else {
Alert.alert(
I18n.t('ERROR_LABEL'),
JSON.stringify(errorValidateIdentification),
[
{
text: I18n.t("OK"), onPress: () => {
this.props.validateIdentificationResetAction();
this.setState({ triggerSubmitClick: false });
}
}
],
{ cancelable: false }
)
}
}
}
onSubmitValidationClient = () => {
const { displayUploadButtons, numeroTelephone } = this.state;
if (displayUploadButtons) {
console.log('TRUE', displayUploadButtons);
this.dataToSendTemp.append('id_network', 1);
this.dataToSendTemp.append('id_country', 1);
this.props.validateIdentificationAction(this.dataToSendTemp, this.state.idIdentification);
} else {
if (this.ckeckIfFieldIsOK(numeroTelephone))
this.numeroTelephoneAnim.shake(800);
else {
this.props.getUserIdentificationAction(numeroTelephone);
}
}
}
onPicture = ({ uri }) => {
this.setState({ image: uri, displayCamera: true });
console.log("URI", uri);
}
onBackToCamera = () => {
this.setState({ image: null, displayCamera: false });
}
renderDialogImage = () => {
return (