/**
 * @format
 * @flow
 */
import React from 'react';
import {
    Alert,
    Animated,
    AsyncStorage,
    BackHandler,
    Dimensions,
    FlatList,
    PermissionsAndroid,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import axios from "axios";
import IMap from './IMap'
import ActionButton from 'react-native-action-button';
import {CardView} from "react-native-cardview"
import {responsiveHeight, responsiveWidth,} from 'react-native-responsive-dimensions';
import {material} from 'react-native-typography';
import {getMakersFrom, getPositionInformation, loadGroupeAgent} from './../../webservice/MapService';
import {getCountryNetwork, readUser} from './../../webservice/AuthApi'
import BaseScreen from './../BaseScreen'
import isEqual from 'lodash/isEqual';
import Button from 'apsl-react-native-button'
import I18n from 'react-native-i18n'
import {IlinkEmitter} from "./../../utils/events"
import _ from 'lodash';
import {RNCamera} from "react-native-camera";

import Configuration from "../../webservice/persistences/Configuration";
import {MaterialDialog} from "react-native-material-dialog";
import {ProgressDialog} from 'react-native-simple-dialogs';
import SnapSlider from 'react-native-snap-slider'
import call from "react-native-phone-call";
import Icon from 'react-native-vector-icons/MaterialIcons';
import Geolocation from 'react-native-geolocation-service';
import InterticielAds from './../ads/InterticielAds'
import SnackBar from 'react-native-snackbar-component'
import {FAB, Surface} from 'react-native-paper'
import BottomSheet from 'reanimated-bottom-sheet'
import MarkerManager from './../../webservice/persistences/MarkerManager'
import {bindActionCreators} from 'redux';
import getAuthApiKey from '../../webservice/AuthKeyApi';
import {connect} from 'react-redux';
import getWalletActivated, {
    getQRCodeDetailAction,
    getQRCodeDetailReset,
    searchUserAction,
    searchUserReset
} from '../../webservice/WalletApi';
import {saveOnesignalIdsAction, saveOnesignalIdsReset} from '../../webservice/OnesignalApi';
import OneSignal from 'react-native-onesignal';
import {saveOnesignalIds} from '../../webservice/IlinkConstants';
import {callingCodes} from "@ideditor/country-coder";
import TextInput from "../../components/TextInput";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import FontAwesomeIcon from "react-native-vector-icons/FontAwesome";
import {Color} from "../../config/Color";
import QRCodeScanner from "react-native-qrcode-scanner";
import Dialog from "react-native-dialog";
import {Typography} from "../../config/typography";

const countries = require("./../../utils/country_code.json")

let geolib = require("geolib")
require('./../../utils/Translations')

const GEOLOCATION_OPTIONS = {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 500,
    useSignificantChanges: false,
    distanceFilter: 0
};
const radioOptions = [{label: "mon Reseau", value: 0}, {label: "Tout", value: 1}]
const theme = require('./../../utils/theme.json');
const route = require('./../../route.json');

const {width: viewportWidth, height: viewportHeight} = Dimensions.get('window');


const slideHeight = responsiveHeight(30) > 270 ? 270 : responsiveHeight(30)
//var Fabric = require('react-native-fabric');
//var { Crashlytics } = Fabric


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

class Home extends BaseScreen {

    static navigationOptions = ({navigation}) => {
        return {
            headerMode: "none",
            headerStyle: {
                display: 'none'
            },
            header: null,
            drawerLabel: navigation.getParam("name", I18n.t('MAP')),
            drawerIcon: ({tintColor}) => (
                <Icon
                    name={'map'}
                    size={24}
                    color={tintColor}
                />
            ),
        }
    };
    static defaultProps = {
        draggableRange: {
            top: responsiveHeight(30),
            bottom: 0
        },
        panel: null
    };

    _draggedValue = new Animated.Value(0)

    renderIcon = icon => ({isActive}) => (
        <Icon size={24} color="white" name={icon}/>
    )

    onLoadMore() {
        const {user, prevRegion, boundarie} = this.state;

        if (user.category === undefined || user.category === null) {

            if (this.promiseRegion) this.promiseRegion.done();

            this.promiseRegion = new Promise(async (resolve, reject) => {
                this.setState({isNeedLoadMore: false, isLoadingMap: true})
                const camera = await this.mapRef.getCamera();//comment this
                const zoom = camera.zoom - 10
                let res = [];

                if (this.state.filternetworkTemp !== undefined) {
                    let net = this.state.filternetworkTemp.id
                    res = this.state.networks.filter(function (item) {
                        return item.id === net
                    });
                }

                if (res.length > 0) {
                    this.setState({isLoadingMap: false})

                    let reseau = res[0];
                    const pos = {longitude: user.longitude, latitude: user.latitude}
                    try {
                        //let data = await loadMarkers(pos, reseau, 5000, this.state.page)
                        let data = await this.loadingMarkers(this.state.myPosition, this.state.filternetwork, this.filterOptions[this.state.increasePas].value);

                        this.treatNewData(pos, data, false)
                    } catch (e) {
                        this.setState({isNeedLoadMore: false, isLoadingMap: false})
                    }
                } else {
                    this.setState({isNeedLoadMore: true, isLoadingMap: false})
                }
                if (this.map) this.map.focusToUser()
                resolve()

            })
        }
    }

    openDrawer = () => {
        this.props.navigation.openDrawer()
    }

    onslidingEvent(event) {
        this.setState({
            maxHeightSliding: event.nativeEvent.layout.height
        });
    }


    onIds = async (device) => {
       // console.log('Device info: ', device);

        AsyncStorage.getAllKeys((err, keys) => {
            AsyncStorage.multiGet(keys, (err, stores) => {
                stores.map(async (result, i, store) => {
                    let key = store[i][0];
                    if (i === 0) {
                        if (!_.isEqual(key, '@config:onesignalIds')) {
                            this._saveOneSignalIds(device.userId);
                           // console.log("FIRST LAUNCH", true);
                            //IlinkEmitter.emit("firstlaunch");
                            this.onFirstLaunch();
                        }
                    }
                });
            });
        });
    }

    onFirstLaunch = () => {
        console.warn("FIRST LAUNCH ON HOME");
        readUser().then(async (user) => {
            //console.log("USER", user);
            if (user) {
                if (user !== undefined) {

                    global.onesignalIds = await this._getOneSignalIds();
                    if (global.onesignalIds) {
                       // console.log("ONESIGNAL", global.onesignalIds);
                        if (user !== undefined) {
                            if (user.category !== undefined) {
                                this.saveOneSignal(false, {
                                    code_membre: user.code_membre,
                                    player_id: global.onesignalIds,
                                    set_default: false
                                });

                                /*                                              this.props.saveOnesignalIdsAction(false, {
                                                                                  code_membre: user.user_code,
                                                                                  player_id: onesignalIds,
                                                                                  set_default: false
                                                                             }); */
                            } else {
                                this.saveOneSignal(true, {
                                    user_code: user.user_code,
                                    player_id: global.onesignalIds,
                                    set_default: false
                                });
                                /*                                         this.props.saveOnesignalIdsAction(true, {
                                                                             user_code: user.user_code,
                                                                             player_id: onesignalIds,
                                                                             set_default: false
                                                                        }); */
                            }
                        }                                                            //this.props.saveOnesignalIdsAction()
                    }

                    //this.props.getWalletActivated(user.agentId);
                }
            }
        });

    }

    saveOneSignal = (isUser, data) => {
        axios({
            url: isUser ? `${saveOnesignalIds}/saveUser` : `${saveOnesignalIds}/saveAgent`,
            method: 'POST',
            data,
            headers: {
                'X-Localization': I18n.currentLocale()
            }
        })
            .then(response => {
                console.warn(response);
                if (response.data.status === 201)
                    this.renderOneSignalResponse(response.data.error);
            })
            .catch(error => {
                console.warn(error);
                if (error.response)
                    this.renderOneSignalResponse(error.response);
                else if (error.request)
                    this.renderOneSignalResponse(error.request);
                else
                    this.renderOneSignalResponse(error.message);
            });
    }

    _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)
        }
    };

    _getOneSignalIds = () => {
        return new Promise(async (resolve, reject) => {
            try {
                const getElement = await AsyncStorage.getItem('@config:onesignalIds');
                resolve(getElement);
            } catch (error) {
                reject(error);
            }
        });
    }

    componentDidMount() {
        //this.onMapReady();//comment thi
        readUser().then(async (user) => {
            if (user) {
                if (user !== undefined) {
                    if (user.phone !== undefined)
                        this.props.getAuthApiKey(user.phone);
                }
            }
        });
        /*           AsyncStorage.getAllKeys((err, keys) => {
                       AsyncStorage.multiGet(keys, (err, stores) => {
                            stores.map((result, i, store) => {
                                 let key = store[i][0];
                                 let value = store[i][1];
                                 console.log('STORAGE VALUE ', `key: ${key} | value: ${value}`);
                            });
                       });
                  }); */

        this.mounted = true;
        const {navigation} = this.props;
        this.markerManager = new MarkerManager()
        this.configuration.getCurrentPubValue().then((value) => {
            try {
                const val = parseInt(value)
                this.setState({isPubShow: val});
            } catch (e) {

            }
        })
        this.focusListener = navigation.addListener("didFocus", () => {
            this.configuration.getCurrentPasValue().then((value) => {
                try {
                    this.setState({pas: parseInt(value)});
                } catch (e) {

                }
            });
            this.componentDidAppear();

        });
        this.blurListener = navigation.addListener("didBlur", (payload) => {
            this.componentDidDisappear()
        })
        this._retrieveData()

        //this.toggleSlidingUp(false)
        if (this.props.coordinate) return;

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.resultSearchUserByName !== null) {
            this.setState({displayDialogResultSearch: true});
        }

        if (nextProps.resultGetQRCodeDetail !== null) {
            if (nextProps.resultGetQRCodeDetail.response !== null) {
                this.setState({userName: '' + nextProps.resultGetQRCodeDetail.response.phone})
            }
        }

        if (nextProps.errorGetQRCodeDetail !== null) {
            if (typeof nextProps.errorGetQRCodeDetail.data !== 'undefined') {
                Alert.alert(
                    I18n.t("ERROR_LABEL"),
                    nextProps.errorGetQRCodeDetail.data.error,
                    [
                        {
                            text: I18n.t("OK"), onPress: () => {
                                this.setState({
                                    displayPhoneField: false,
                                    userName: ''
                                });
                                this.props.searchUserReset();
                                this.props.getQRCodeDetailReset();
                            }
                        }
                    ],
                    {cancelable: false}
                );
            }
        }

    }


    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) {
                readUser().then((user) => {
                    if (user) {
                        if (user.category !== undefined && user.category !== null) {
                            const myPosition = {
                                latitude: parseFloat(user.latitude),
                                longitude: parseFloat(user.longitude)
                            }

                            const reg = {
                                latitude: myPosition.latitude,
                                longitude: myPosition.longitude,
                                latitudeDelta: 0.03,
                                longitudeDelta: 0.01,
                            }
                            this.setState({myPosition: myPosition});
                            this.mapRef.animateToCoordinate({
                                latitude: myPosition.latitude,
                                longitude: myPosition.longitude
                            }, 1000)
                            this.mapRef.animateToRegion(reg, 1000)
                            this.setState({isLoading: false, isLoadingMap: false, loadingDialog: false})

                            if (user.category !== "geolocated") {
                             //   console.log("THIS IS CALL");
                                this.showMyMembers();
                            } else {
                                if (myPosition.latitude <= 0 && myPosition.longitude <= 0) {
                                    this.props.navigation.push(route.updateinfo);
                                }
                            }

                        } else {
                            this.getPosition();
                            this.watchLocation();
                        }
                    }
                })

            } else {
            }
        } catch (err) {
           // console.log(err)
        }
    }

    _storeData = async (position) => {
        try {
            await AsyncStorage.setItem('position', JSON.stringify(position));
        } catch (error) {
            console.warn(error)
        }
    };

    watchLocation() {
        this.watchID = Geolocation.watchPosition((position) => {
            const myLastPosition = this.state.myPosition;
            let myPosition = position.coords;
            const oldPosition = this.state.oldPosition
            if (!myLastPosition || (myPosition.longitude !== myLastPosition.longitude || myPosition.latitude !== myLastPosition.latitude)) {
                if (myPosition.longitude !== 0 && myPosition.latitude !== 0)
                    this._storeData(myPosition)

                if (isEqual(this.state.region, {}) || isEqual(this.state.region, undefined) || isEqual(this.state.region, null))
                    if (!this.state.myPosition.longitude && !this.state.myPosition.latitude) {
                        if (this.mapRef !== null && this.mapRef !== undefined) {
                            this.mapRef.animateToRegion({
                                latitude: myPosition.latitude,
                                longitude: myPosition.longitude,
                                latitudeDelta: 0.03,
                                longitudeDelta: 0.01,
                            }, 1000)
                            this.mapRef.animateCamera({
                                center: this.myPosition,
                                pitch: 0,
                                heading: 0,
                                altitude: 0,

                                zoom: 12
                            }, 1000)
                        }


                    }
                this.setState({
                    region: {
                        latitude: myPosition.latitude,
                        longitude: myPosition.longitude,
                        latitudeDelta: 0.003,
                        longitudeDelta: 0.004
                    }
                });
                this.setState({myPosition: myPosition});
                if (this.map) this.map.focusToUser()

            }
        }, (error => console.log("wat   s", error)), GEOLOCATION_OPTIONS);
    }

    getNetworks(pays) {
        if (pays) {
            getCountryNetwork(pays).then((result) => {
                this.reseaux = [];
                let networks = result;

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

                this.setState({networks: this.reseaux});
                let c = this.reseaux.filter((item) => {
                    return item.name.includes(this.state.network);
                })
                if (this.state.user.category === undefined || this.state.user.category === null) {
                    if (c.length > 0 && pays) {

                        this.setState({filternetwork: c[0], myNetwork: c[0], filternetworkTemp: c[0]})
                        this.retrieveAllPoint(pays)

                    } else {
                        if (this.state.user) {
                            if (!this.state.user.category)
                                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: () => {
                                                if (pays !== null && pays !== undefined)
                                                    this.getNetworks(pays)
                                                else
                                                    this.requestCameraPermission()
                                            }
                                        }

                                    ],
                                    {cancelable: false}
                                )
                        }
                    }
                }
            }, (err) => {
                //  Crashlytics.log("get networks"+e.message)
                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: () => {
                                if (pays !== null && pays !== undefined)
                                    this.getNetworks(pays)
                                else
                                    this.requestCameraPermission()

                            }
                        }

                    ],
                    {cancelable: false}
                )
            })


        } else {
            console.log("get network missing pays")
            var msg = "impossible de récupérer le nom du pays";
            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.requestCameraPermission()
                        }
                    }
                ],
                {cancelable: false}
            )
        }

    }

    getPosition(options = null) {
        console.log("on get position")
        Geolocation.getCurrentPosition(
            (position) => {
                const myLastPosition = this.state.myPosition;
                const myPosition = position.coords;
                const oldPosition = this.state.oldPosition

                if (!isEqual(myPosition, myLastPosition) && myPosition.longitude !== 0 && myPosition.latitude !== 0 || myLastPosition) {
                    if (this.map) this.map.focusToUser()
                    getPositionInformation(myPosition).then((response) => {
                        if (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
                                                })
                                            }
                                        }
                                    }
                                    for (let i of countries) {
                                        if (i.code === shortcountry) {
                                            this.setState({indicatif: i.dial_code})
                                            this.getNetworks(i.dial_code)
                                        }
                                    }

                                }

                            } else {
                                console.log("on else result 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.getPosition(options)
                                            }
                                        }

                                    ],
                                    {cancelable: false}
                                )
                            }
                        } else {
                            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.getPosition(options)
                                        }
                                    }

                                ],
                                {cancelable: false}
                            )
                        }
                    });
                    const reg = {
                        latitude: myPosition.latitude,
                        longitude: myPosition.longitude,
                        latitudeDelta: 0.03,
                        longitudeDelta: 0.01,
                    }
                    this.setState({myPosition: myPosition, region: reg});
                    if (this.mapRef && !this.state.myPositionIsAnimated) {
                        //comment
                        this.mapRef.animateCamera({
                            center: myPosition,
                            pitch: 0,
                            heading: 0,
                            altitude: 5,
                            zoom: 12
                        }, 1000);
                        this.setState({myPositionIsAnimated: true})

                    }

                } else console.warn("errror")
            },
            (error) => {
                console.warn(error.message)
                switch (error.code) {
                    case 3:
                        if (this.state.oldPosition) {
                            this.treatPosition(this.state.oldPosition)
                        }
                        break;
                    default:
                        //Crashlytics.log(error.message)
                       // console.log("onjjj", error.message)

                    /* 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.getPosition(options)    }}

                         ],
                         {cancelable:false}
                     )*/
                }
            },
            GEOLOCATION_OPTIONS
        );

    }

    componentDidDisappear() {
        BackHandler.removeEventListener('hardwareBackPress', this.backPressed);

    }

    componentDidAppear() {
        BackHandler.addEventListener('hardwareBackPress', this.backPressed);
        // this.props.start();

        readUser().then((user) => {
            if (user) {
                if (user.category) {

                    this.setState({user: user})
                    this.setState({network: user.network});

                    const myPosition = {
                        latitude: parseFloat(user.latitude),
                        longitude: parseFloat(user.longitude)
                    }

                    const reg = {
                        latitude: myPosition.latitude,
                        longitude: myPosition.longitude,
                        latitudeDelta: 0.03,
                        longitudeDelta: 0.01,
                    }
                    this.setState({myPosition: myPosition});
                    this.refocusMap(true);
                }

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

            }
        })
    }

    componentWillUnmount() {
        OneSignal.removeEventListener('ids', this.onIds);
        this.mounted = false;

        this.blurListener.remove();
        this.focusListener.remove()
        if (this.watchID) Geolocation.clearWatch(this.watchID);
    }


    backPressed = () => {
        Alert.alert(
            I18n.t('EXIT_TITLE'),
            I18n.t('EXIT_DESC'),
            [
                {text: I18n.t('NO'), onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
                {text: I18n.t("YES"), onPress: () => BackHandler.exitApp()},
            ],
            {cancelable: false});
        return true;
    }

    constructor(props) {
        super(props);
        this.state = this.geInitialState();
        this.mounted = false;
        this.configuration = new Configuration();
        IlinkEmitter.on("firstlaunch", this.onFirstLaunch);
        this.filterOptions = [
            {value: 5, label: "5 km"},
            {value: 15, label: "15 km"},
            {value: 20, label: "20 km"},
            {value: 25, label: "25 km"}
        ];
        Icon.getImageSource('md-car', 24, 'white').then((resutl) => {
            this.setState({caricon: resutl})
        });
        //this._renderFavoriteIcon = this._renderFavoriteIcon.bind(this);
        this.makeMarkerInformation = this.makeMarkerInformation.bind(this);

        //IlinkEmitter.on("langueChange", this.updateLangue.bind(this))
        OneSignal.addEventListener('ids', this.onIds);
        global.appHasLoaded = true;
        this.configuration._getPubData().then((value) => {
            //console.log("PUBLICITE function: ", value);
            this.setState({publicite: value});
        }).catch((e) => {
            //console.log("PUBLICITE Error: ", e);
        });
    };

    /*      updateLangue() {
              this.props.navigation.setParams({ name: I18n.t('MAP') })
              this.forceUpdate();
         } */

    _getOneSignalIds = () => {
        return new Promise(async (resolve, reject) => {
            try {
                const getElement = await AsyncStorage.getItem('@config:onesignalIds');
                resolve(getElement);
            } catch (error) {
                reject(error);
            }
        });
    }

    _saveOneSignalIds = async (ids) => {
        try {
            await AsyncStorage.setItem('@config:onesignalIds', ids);
        } catch (error) {
            console.warn(error);
        }
    }


    makeCardSearch() {
        /* if (!this.state.isPubShow) { */
        return (
            <View style={styles.topBar}>
                <Surface

                    style={{
                        elevation: 4,
                        borderRadius: 10
                    }}>
                    <View style={{
                        flexDirection: 'row',
                        alignSelf: 'center',
                        justifyContent: 'center',
                        flex: 1,
                        borderRadius: 10,
                        margin: 10,
                        alignItems: 'center',
                        height: 48,
                    }}>
                        <TouchableOpacity onPress={() => this.openDrawer()}
                        >

                            <Text
                                style={styles.hambuger}
                            >
                                Menu
                            </Text>

                        </TouchableOpacity>
                        <View style={{flex: 1}}></View>

                        <Text style={{
                            backgroundColor: this.state.myNetwork.id === this.state.filternetwork.id ? theme.primary : theme.accent,
                            padding: 5,
                            color: "white",
                            marginRight: 10,
                            fontSize: 10,
                            borderRadius: 12,
                        }}
                        >{this.state.filternetwork.name ? this.state.filternetwork.name : this.state.network}</Text>
                        {this.renderSupplementInformation()}
                    </View>
                    {this.showLoadingMapView()}

                </Surface>

            </View>

        )
        /* } */

    }

    renderSupplementInformation() {

        if (this.state.user && this.state.user.category === "geolocated") {
            return (<View/>)
        } else

            return (<View style={{flexDirection: "row"}}>
                    <View style={{
                        backgroundColor: "#FFFFFFA0",
                        justifyContent: 'center',
                        alignItems: 'center',
                        alignSelf: 'center'
                    }}>
                        <Text>{this.state.markers.length + " " + (this.state.currentNetworkSize === 0 ? "" : "/" + this.state.currentNetworkSize)} </Text>

                    </View>
                    <TouchableOpacity
                        onPress={() => {
                            this.setState({page: this.state.page + 1})
                            this.onLoadMore()
                        }}
                        style={{
                            borderRadius: 12,
                            height: 32,
                            width: 32,
                            backgroundColor: "white",
                            borderColor: "transparent",
                        }}>
                        <Icon name={this.state.markers.length >= this.state.currentNetworkSize ? "close" : "refresh"}
                              size={32}
                              color={this.state.markers.length >= this.state.currentNetworkSize ? "red" : "grey"}
                        />
                    </TouchableOpacity>
                </View>
            )
    }

    _renderMarker2() {
        let {currentMarker, myPosition} = this.state;
        let marker = currentMarker
        const ma = {latitude: parseFloat(currentMarker.latitude), longitude: parseFloat(currentMarker.longitude)}
        const meter_distance = geolib.getDistance(myPosition, ma);

        const distanceTxt = (meter_distance > 900 ?
            (meter_distance / 1000) + " Km" : meter_distance + "m") + I18n.t('TO_YOU')

        var name = marker.lastname === null ? marker.adresse : marker.lastname

        return (<View style={{flex: 1, backgroundColor: "white"}}>
            <View style={{
                flexDirection: "row",
                justifyContent: "flex-end",
                alignItems: 'center',
                backgroundColor: "white"
            }}>
                <Text style={markerDetails.title}>{name}</Text>
                <Icon.Button name={"close"} size={24} color={"red"} backgroundColor={"transparent"}
                             onPress={() => {
                                 this.toggleSlidingUp(false)

                             }
                             }></Icon.Button>
            </View>
            <Text style={markerDetails.subtitle2}>{marker.adresse}</Text>
            <View style={{flexDirection: "row", alignItems: "center"}}>
                <Text style={markerDetails.reseau}>{marker.network}</Text>
                <Text style={markerDetails.solde}>{I18n.t('SOLDE_UNVAIBLE')}</Text>
            </View>
            <Text style={markerDetails.reseau}>{distanceTxt}</Text>
            <View
                style={{flexDirection: 'row', marginTop: responsiveHeight(3), marginLeft: 10}}
            >
                {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()}
                <Button
                    style={{
                        backgroundColor: "white",
                        width: responsiveWidth(30),
                        height: 36,
                        marginLeft: 5, borderRadius: 100, borderColor: "#9e9e9e", justifyContent: 'center'
                    }}
                    onPress={() => this.callItem(marker)}
                >
                    <View
                        style={{flexDirection: 'row'}}
                    >
                        <Icon
                            name="phone"
                            size={16}
                            color={theme.primary}
                            style={{alignSelf: 'center'}}
                        />
                        <Text
                            style={{fontSize: 15, color: '#9e9e9e', marginLeft: responsiveWidth(2)}}
                        >{I18n.t("CALL")}</Text></View>
                </Button>
            </View>

        </View>)
    }

    _renderItemMarkerdetails(markers) {
        let marker = markers
        if (marker !== undefined && marker !== null) {
            let {currentMarker, myPosition} = this.state;
            const ma = {latitude: parseFloat(currentMarker.latitude), longitude: parseFloat(currentMarker.longitude)}
            const meter_distance = geolib.getDistance(myPosition, ma);

            const distanceTxt = (meter_distance > 900 ?
                (meter_distance / 1000) + " Km" : meter_distance + "m") + I18n.t('TO_YOU')

            var name = marker.lastname === null ? marker.adresse : marker.lastname
            return (<CardView style={markerDetails.container}
                              cardElevation={2}
                              cardMaxElevation={2}
                              cornerRadius={5}
            >
                <View style={{flexDirection: "row", justifyContent: "flex-end", alignItems: 'center'}}>
                    <Text style={markerDetails.title}>{name}</Text>
                    <Icon.Button name={"close"} size={24} color={"red"} backgroundColor={"transparent"}
                                 onPress={() => {
                                     this.toggleSlidingUp(false)
                                 }
                                 }></Icon.Button>
                </View>
                <Text style={markerDetails.subtitle2}>{marker.adresse}</Text>
                <View style={{flexDirection: "row", alignItems: "center"}}>
                    <Text style={markerDetails.reseau}>{marker.network}</Text>
                    <Text style={markerDetails.solde}>{I18n.t('SOLDE_UNVAIBLE')}</Text>
                </View>
                <Text style={markerDetails.reseau}>{distanceTxt}</Text>

                <View
                    style={{flexDirection: 'row', marginTop: responsiveHeight(3), marginLeft: 10}}
                >
                    {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()}
                    <Button
                        style={{
                            backgroundColor: "white",
                            width: responsiveWidth(30),
                            height: 36,
                            marginLeft: 5, borderRadius: 100, borderColor: "#9e9e9e", justifyContent: 'center'
                        }}
                        onPress={() => this.callItem(marker)}
                    >
                        <View
                            style={{flexDirection: 'row'}}
                        >
                            <Icon
                                name="phone"
                                size={16}
                                color={theme.primary}
                                style={{alignSelf: 'center'}}
                            />
                            <Text
                                style={{fontSize: 15, color: '#9e9e9e', marginLeft: responsiveWidth(2)}}
                            >{I18n.t("CALL")}</Text></View>
                    </Button>
                </View>
            </CardView>);
        }
    }

    renderCurrentMarker(marker) {
        if (marker) {
            return (<View>
                <View style={{flexDirection: "row", justifyContent: "flex-end", alignItems: 'center'}}>
                    <Text style={markerDetails.title}>{name}</Text>
                    <Icon.Button name={"close"} size={24} color={"red"} backgroundColor={"transparent"}
                                 on dPress={() => {
                        this.toggleSlidingUp(false)
                    }
                    }></Icon.Button>
                </View>
                <Text style={markerDetails.title}>{marker.adresse}</Text>
                <View style={{flexDirection: "row"}}>
                    <Text style={markerDetails.reseau}>{marker.network}</Text>
                    <Text style={markerDetails.solde}>{I18n.t('SOLDE_UNVAIBLE')}</Text>
                </View>
                <Text style={markerDetails.reseau}>{distanceTxt}</Text>

                <View
                    style={{flexDirection: 'row', marginTop: responsiveHeight(3), marginLeft: 10}}
                >
                    {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()}
                    <Button
                        style={{
                            backgroundColor: "white",
                            width: responsiveWidth(30),
                            height: 36,
                            marginLeft: 5, borderRadius: 100, borderColor: "#9e9e9e", justifyContent: 'center'
                        }}
                        onPress={() => this.callItem(marker)}
                    >
                        <View
                            style={{flexDirection: 'row'}}
                        >
                            <Icon
                                name="phone"
                                size={16}
                                color={theme.primary}
                                style={{alignSelf: 'center'}}
                            />
                            <Text
                                style={{fontSize: 15, color: '#9e9e9e', marginLeft: responsiveWidth(2)}}
                            >{I18n.t("CALL")}</Text></View>
                    </Button>
                </View></View>)
        }
    }

    callItem(marker) {
        const args = {
            number: marker.phone, // String value with the number to call
            prompt: false // Optional boolean property. Determines if the user should be prompt prior to the call
        }
        call(args).catch((e) => console.log(e))
    }

    makeMarkerInformation() {
        let {currentMarker, myPosition} = this.state;
        // console.log(geolib.getDistance(myPosition,currentMarker))
        if (currentMarker !== undefined && currentMarker !== null) {
            // this.setState({stateSheet:BottomSheetBehavior.STATE_EXPANDED})
            return this._renderItemMarkerdetails(currentMarker);
        } else {
            return (<Text>Impossible de'afficher l'element</Text>)
        }
    }

    makeActionButon() {
        let cu = this.state.user;
        if (cu) {
            switch (cu.category) {
                case "super":
                    return this.getSuperActionButton();
                    break;
                case "geolocated":
                    return this.geoLocatedAction();
                    break;
                case "hyper":
                    return this.getHypervisorActionButton();
                    break;
                default:
                    return this.getSimpleActionButton();
                    break;
            }
        }
    }

    getSuperActionButton() {
        return (<ActionButton
            buttonColor={theme.accent}
        >
            <ActionButton.Item buttonColor='#3498db' title={I18n.t("SEARCH")}
                               onPress={() => {
                                   this.setState({dialogSearchUser: true});
                               }}
                               size={48}
            >
                <Icon name="search" style={styles.actionButtonIcon}/>
            </ActionButton.Item>
            <ActionButton.Item buttonColor='#3498db' title={I18n.t("MY_GROUP")} onPress={() => this.showMyMembers()}
                               size={48}
            >
                <Icon name="group-work" style={styles.actionButtonIcon}/>
            </ActionButton.Item>
            <ActionButton.Item buttonColor='#3498db' title={I18n.t("REPOSITIONNING")}
                               onPress={() => this.refocusMap(false)}
                               size={48}
            >
                <Icon name="person-pin" style={styles.actionButtonIcon}/>
            </ActionButton.Item>

            <ActionButton.Item buttonColor={theme.primary} title={I18n.t("CHANGE_MAP")}
                               onPress={() => {
                                   this.onMapTypeChange();
                               }}
                               size={48}
            >
                <Icon name="layers" style={styles.actionButtonIcon}/>
            </ActionButton.Item>

        </ActionButton>)

    }

    getSimpleActionButton() {
        return (
            <ActionButton
                ref={(r) => this.actionButton = r}
            >
                <ActionButton.Item buttonColor='#3498db' title={I18n.t("FILTER")}
                                   onPress={() => this.showFilterDialog()}
                                   size={48}
                >
                    <Icon name="filter-list" style={styles.actionButtonIcon}/>
                </ActionButton.Item>
                <ActionButton.Item buttonColor='#3498db' title={I18n.t("SEARCH")}
                                   onPress={() => {
                                       this.setState({dialogSearchUser: true});
                                   }}
                                   size={48}
                >
                    <Icon name="search" style={styles.actionButtonIcon}/>
                </ActionButton.Item>
                <ActionButton.Item buttonColor='#3498db' title={I18n.t("REPOSITIONNING")}
                                   onPress={() => this.refocusMap(false)}
                                   size={48}
                >
                    <Icon name="person-pin" style={styles.actionButtonIcon}/>
                </ActionButton.Item>
                <ActionButton.Item buttonColor='#9b59b6' title={I18n.t("CHANGE_MAP")}
                                   onPress={() => {
                                       this.onMapTypeChange();
                                   }
                                   }
                                   size={48}
                >
                    <Icon name="layers" style={styles.actionButtonIcon}/>
                </ActionButton.Item>
                <ActionButton.Item buttonColor='#3498db' title={I18n.t("PRINT_MY_NETWORK")}
                                   size={48}
                                   onPress={() => {
                                       this.showMynetworkMap();
                                   }}>
                    <Icon name="group-work" style={styles.actionButtonIcon}/>
                </ActionButton.Item>
                <ActionButton.Item buttonColor='#3498db' title={I18n.t("CHANGE_NETWORK")}
                                   size={48}
                                   onPress={() => {
                                       this.showNewDialogNetwork();
                                   }}>
                    <Icon name="rss-feed" style={styles.actionButtonIcon}/>
                </ActionButton.Item>

            </ActionButton>

        )

    }

    toggleSlidingUp(state) {
        if (state && this.bottomSheetRef) {
            this.bottomSheetRef.snapTo(1)
            this.setState({showcurentMarker: state})
        } else if (!state) this.bottomSheetRef.snapTo(0)

        const height = slideHeight
        let initialValue = !state ? 0 : height,
            finalValue = !state ? height : 0;


        this.setState({
            panelVisible: state
        });
        if (!state && this.state.needRoad) {
            this.setState({needRoad: false});
        }


        this.state.animation.setValue(initialValue);  //Step 3
        Animated.timing(     //Step 4
            this.state.animation,
            {
                toValue: finalValue,
                duration: 200,
            }
        ).start((animation) => {
            if (!state && this.map) {
                this.map.focusToUser()
            }
        });
    }

    makeSlidingUp() {
        /*return (
            <Animated.View
                style={[styles.slidingup, {translateY: this.state.animation}]}
                height={slideHeight}
                visible={this.state.panelVisible}
                onLayout={(event) => this.onslidingEvent(event)}
                ref={(c) => this.panel = c}
                onRequestClose={() => this.setState({panelVisible: false, needRoad: false})}>
                <View style={{flex: 1}}>
                    {this.makeMarkerInformation()}
                </View>
            </Animated.View>)*/
        return (<BottomSheet
            ref={(r) => {
                this.bottomSheetRef = r
            }}
            snapPoints={[0, "30%"]}
            renderHeader={() => this.markerView()}
        />)
    }

    /* _renderFavoriteIcon() {
         const { top, bottom } = this.props.draggableRange
         const draggedValue = this._draggedValue.interpolate({
              inputRange: [bottom, top],
              outputRange: [1, 0],
              extrapolate: 'clamp'
         })
         const transform = [{ scale: draggedValue }]
         return (
              <TouchableNativeFeedback onPress={() => {
                   this.setState({ needRoad: true })
              }}>
                   <Animated.View style={[styles.favoriteIcon, { transform }]}>
                        <Icon
                             name="car"
                             size={24}
                             color='white'
                             style={{ alignSelf: 'center' }}
                        />
                   </Animated.View>
              </TouchableNativeFeedback>
         )
    } */

    geInitialState() {
        return {
            isSaveOneSignalDisplay: false,
            region: {
                latitude: 0,
                longitude: 0,
                latitudeDelta: 0.015,
                longitudeDelta: 0.0121,
            },
            pas: 100,
            prevRegion: {
                latitude: 0,
                longitude: 0,
            },
            increasePas: 0,
            isPubShow: true,
            loadingDialog: true,
            textreach: "",
            currentNetworkSize: 0,
            markersearchfilter: [],
            animation: new Animated.Value(0),
            myPosition: null,
            currentMarker: null,
            filterNetworkOption: radioOptions[1],
            needRoad: false,
            initialAnim: false,
            filternetwork: {},
            destinationPosition: {},
            panelVisible: false,
            markers: [],
            isNeedLoadMore: false,
            isLoadingMap: false,
            value: 5,
            page: 0,
            valuePosition: 0,
            markerfilter: null,
            allpoint: [],
            typeMap: 'standard',
            indexTypeMap: 0,
            user: null,
            snack_visible: false,
            snack_text_message: "",
            networks: [],
            dialogSliderVisible: false,
            showProgress: false,
            myNetwork: {},
            dialogNetworkVisible: false,
            myPositionMarkerText: I18n.t("YOUR_THERE"),
            isSaveOneSignalOK: false,
            publicite: null,
            userName: '',
            isNumeroAssureSearch: false,
            isPhoneAssureSearch: false,
            showQRCodeScanner: false,
            displayDialogResultSearch: false,
            dialogSearchUser: false
        };
    };

    onMarkerPress(marker) {
        console.warn(marker)
        this.setState({currentMarker: marker});
        this.toggleSlidingUp(true)
    }

    onMapTypeChange() {
        var newState = {index: this.state.indexTypeMap, text: this.state.typeMap};
        newState.index = newState.index + 1;
        newState.index = newState.index % 3;

        switch (newState.index) {
            default:
                newState.text = 'standard';
                break;
            case 1:
                newState.text = 'hybrid';
                break;
            case 2:
                newState.text = "terrain";
                break;
        }
        this.setState({indexTypeMap: newState.index, typeMap: newState.text});
    }

    /*
            <IMap style={{...StyleSheet.absoluteFillObject,backgroundColor:'red'}}
                        ref={(re)=>{
                            this.map=re
                            if(re!=null) {
                                this.mapRef = re.getMapRef();
                            }
                        }}
                        typeMap={this.state.typeMap}
                        onMarkerClick={(e)=>this.onMarkerPress(e)}
                        network={this.state.filternetwork}
                        initialRegion={this.state.region}
                        markers={this.state.markers}
                        selectedMarker={this.state.currentMarker}
                        myNetwork={this.state.myNetwork}
                        lang={this.state.lang}
                        myPosition={this.state.myPosition}
                        onMapReady={()=>{
                            readUser().then((user) => {
                                if (user) {
                                    this.setState({user: user})
                                    this.setState({network: user.network});
                                    if (Platform.OS === 'android') {
                                        this.requestCameraPermission();
                                    } else {
                                        this.getPosition();
                                        this.watchLocation();
                                    }

                                }
                            })

                        }}
                        needRoad={this.state.needRoad}
                        onNeedRoadReady={(data)=>{
                            this.setState({showProgress: false})
                        }}
                        onNeedRoadError={(message)=>{
                            this.setState({showProgress: false})
                            Alert.alert(I18n.t("PROBLEM_OCCUR"),I18n.t("PROBLEM_OCCUR_DIRECTION"),[{text:"Ok",onPress:()=>{}}])
                        }}
                    />*/
    showInterticiel() {
        //console.log("PUBLICITE", this.state.publicite);

        if (!_.isNil(this.state.publicite) && !_.isNil(this.state.user)) {
            if (this.state.isPubShow) {
                return (<InterticielAds
                    closeIntersticiel={() => this.setState({isPubShow: false})}
                    navigation={this.props.navigation}
                />)
            }
        } else return null;


    }

    renderBottomHome() {
        return (
            <View style={{flex: 1, backgroundColor: "lightblue"}}>
                <IMap
                    ref={(re) => {
                        this.map = re
                        if (re != null) {
                            this.mapRef = re.getMapRef();
                        }
                    }}
                    typeMap={this.state.typeMap}
                    onMarkerClick={(e) => this.onMarkerPress(e)}
                    network={this.state.filternetwork}
                    initialRegion={this.state.region}
                    markers={this.state.markers}
                    selectedMarker={this.state.currentMarker}
                    myNetwork={this.state.myNetwork}
                    lang={this.state.lang}
                    myPosition={this.state.myPosition}
                    onMapReady={() => {

                        readUser().then((user) => {
                            if (user) {
                                this.setState({user: user})
                                this.setState({network: user.network});

                                if (user.category) {
                                    this.setState({loadingDialog: false})
                                    if (user.category !== "geolocated") {
                                        this.showMyMembers();
                                    } else {
                                        if (myPosition.latitude <= 0 && myPosition.longitude <= 0) {
                                            this.props.navigation.push(route.updateinfo);
                                        }
                                    }
                                } else {
                                    if (Platform.OS === 'android') {
                                        this.requestCameraPermission();
                                    } else {
                                        //this.getPosition();
                                        this.watchLocation();
                                    }
                                }
                            }
                        })

                    }}
                    needRoad={this.state.needRoad}
                    onNeedRoadReady={(data) => {
                        this.setState({showProgress: false})
                    }}
                    onNeedRoadError={(message) => {
                        this.setState({showProgress: false})
                        Alert.alert(I18n.t("PROBLEM_OCCUR"), I18n.t("PROBLEM_OCCUR_DIRECTION"), [{
                            text: "Ok",
                            onPress: () => {
                            }
                        }])
                    }}
                />
                {this.makeCardSearch()}
                <BottomSheet
                    ref={(r) => {
                        this.bottomSheetRef = r
                    }}
                    snapPoints={[60, "30%", "100%"]}
                    renderHeader={() => this.renderHeader()}
                />
            </View>
        )
    }

    renderInner() {
        return (<View style={{flex: 1, backgroundColor: "green"}}>
            <Text>Freud junior</Text>
        </View>)
    }

    markerView() {
        if (this.state.currentMarker) return this._renderMarker2()
    }

    renderHeader() {
        return (<React.Fragment>
            <View style={{
                position: "absolute",
                width: 32,
                height: this.state.currentMarker ? 200 : 100,
                bottom: 80,
                right: 0,
                justifyContent: 'center'
            }}>
                <ActionButton size={32} style={{marginRight: 15}} buttonColor="white"/>
                <ActionButton size={42}
                              renderIcon={() => {
                                  return (<Icon name="group-work" style={styles.actionButtonIcon}/>
                                  )
                              }}
                              style={{marginTop: 40, marginRight: 20}} buttonColor={theme.primary}/>
            </View>

            <View style={{flex: 1, backgroundColor: "white"}}>
                {this.markerView()}
                {this.renderFilterMarker()}

                <View
                    style={{flexDirection: 'row', height: 60, justifyContent: 'space-evenly', alignItems: 'flex-end'}}>
                    <View style={{
                        flexDirection: 'row',
                        flex: 1,
                        marginBottom: 10,
                        justifyContent: 'space-around',
                        alignItems: 'flex-end'
                    }}>
                        <FAB small
                             icon={!this.state.showFilterDistance ? "filter" : "close"}
                             color={theme.primary}
                             style={{backgroundColor: "white"}}

                             onPress={() => {
                                 if (!this.state.showFilterDistance) {
                                     this.bottomSheetRef.snapTo(2)
                                     this.setState({showFilterDistance: true})
                                 } else {
                                     this.bottomSheetRef.snapTo(0)
                                     this.setState({showFilterDistance: false})

                                 }
                             }
                             }/>
                        <FAB
                            small
                            icon={"add"}
                            color={"white"}
                            style={{backgroundColor: theme.primary}}
                            onPress={() => {
                                this.bottomSheetRef.snapTo(2)
                                this.setState({showdialogNetworkVisible: true})
                            }}
                        />

                    </View>
                    {this.makeMarkerButton()}
                </View>
            </View>
        </React.Fragment>)
    }

    renderFilterMarker() {
        if (this.state.showFilterDistance)
            return (<View
                style={{height: responsiveHeight(80), justifyContent: 'center', backgroundColor: 'white', margin: 20}}>
                <View style={{height: responsiveHeight(30), justifyContent: 'center'}}>
                    <Text>{I18n.t('TEXT_FILTER_DISTANCE')} </Text>
                    <SnapSlider
                        items={this.filterOptions}
                        defaultItem={this.state.valuePosition}
                        labelPosition="bottom"
                        onSlidingComplete={(item) => this.slidingComplete(item)}
                    />
                    <Text>
                        <Text style={{fontWeight: "bold"}}>
                            {(this.state.value === undefined ? 0 : this.state.value)}</Text> km {I18n.t("DISTANCE_ARROUND")}
                    </Text>


                </View>
                <View style={{flexDirection: "row", flex: 1}}>
                    <Button style={{flex: 1}}/>
                    <Button style={{flex: 1}}/>

                </View>
            </View>)
    }

    makeMarkerButton() {
        if (this.state.currentMarker) {
            return (
                <View style={{flex: 2, flexDirection: 'row', justifyContent: 'flex-end', marginEnd: 20}}>
                    {!this.state.needRoad ? this.showBtnItineraire() : this.showBtnClose()}
                    <Button
                        style={{
                            backgroundColor: "white",
                            width: responsiveWidth(26),
                            height: 36,
                            marginLeft: 5, borderRadius: 100, borderColor: "#9e9e9e", justifyContent: 'center'
                        }}
                        onPress={() => this.callItem(marker)}
                    >
                        <View
                            style={{flexDirection: 'row'}}
                        >
                            <Icon
                                name="phone"
                                size={16}
                                color={theme.primary}
                                style={{alignSelf: 'center'}}
                            />
                            <Text
                                style={{fontSize: 15, color: '#9e9e9e', marginLeft: responsiveWidth(2)}}
                            >{I18n.t("CALL")}</Text></View>
                    </Button>
                </View>)
        } else return (<View style={{flex: 2, flexDirection: 'row', justifyContent: 'flex-end', marginEnd: 20}}>
        </View>)

    }

    renderOneSignalResponse = (message) => {
        /*           Alert.alert(
                       I18n.t('PHISIC_SECURITY'),
                       "Message",
                       [{ text: "OK" }]
                  ); */
        Alert.alert(
            I18n.t('PHISIC_SECURITY'),
            message,
            [
                {

                    text: I18n.t('REFUSED'),
                    onPress: () => {
                        BackHandler.exitApp();
                    }
                },
                {
                    text: I18n.t("SUBMIT_LABEL"), onPress: () => {
                        readUser().then((user) => {
                            if (user) {
                                if (user.category !== undefined) {
                                    this.saveOneSignal(false, {
                                        code_membre: user.code_membre,
                                        player_id: global.onesignalIds,
                                        set_default: true
                                    });
                                } else {
                                    this.saveOneSignal(true, {
                                        user_code: user.user_code,
                                        player_id: global.onesignalIds,
                                        set_default: true
                                    });
                                }
                            }
                        });
                    }
                }


            ],
            {cancelable: false}
        )
    }

    renderOldHome() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="#00000030"
                    barStyle="light-content"
                    translucent={true}
                />
                {/* Start here to comment */}
                {
                    (this.state.loadingDialog || this.props.loading) ?
                        <View
                            style={{
                                position: "absolute",
                                zIndex: 1,
                                backgroundColor: "#00000050",
                                width: this.state.loadingDialog ? responsiveWidth(100) : 0,
                                height: this.state.loadingDialog ? responsiveHeight(100) : 0,
                                flex: 1,
                                justifyContent: 'center',
                                alignItems: 'center'
                            }}

                        >
                            <Text style={{
                                fontSize: 20,
                                color: 'white',
                                fontWeight: 'bold'
                            }}>{I18n.t("LOADING_DOTS")}</Text>
                        </View> : null
                }
                <IMap
                    ref={(re) => {
                        this.map = re
                        if (re != null) {
                            this.mapRef = re.getMapRef();
                        }
                    }}
                    typeMap={this.state.typeMap}
                    onMarkerClick={(e) => this.onMarkerPress(e)}
                    network={this.state.filternetwork}
                    initialRegion={this.state.region}
                    markers={this.state.markers}
                    selectedMarker={this.state.currentMarker}
                    myNetwork={this.state.myNetwork}
                    lang={this.state.lang}
                    myPosition={this.state.myPosition}
                    onMapReady={Platform.OS === 'android' ? this.onMapReady : null}
                    onLayout={Platform.OS === 'ios' ? this.onMapReady : null}
                    needRoad={this.state.needRoad}
                    onNeedRoadReady={(data) => {
                        this.setState({showProgress: false})
                    }}
                    onNeedRoadError={(message) => {
                        this.setState({showProgress: false})
                        Alert.alert(I18n.t("PROBLEM_OCCUR"), I18n.t("PROBLEM_OCCUR_DIRECTION"), [{
                            text: "Ok",
                            onPress: () => {
                                _.isNil(user.latitude)
                            }
                        }])
                    }}
                />
                {this.makeCardSearch()}
                {this.showInterticiel()}
                {this.makeSlidingUp()}
                {this.makeDialogLoader()}
                {this.makeDistanceDialog()}
                {this.makeNetworkChangeDialog()}
                {this.renderSearchUser()}
                {this.state.showQRCodeScanner && this.renderDialogQRCodeScanner()}
                {this.state.displayDialogResultSearch && this.renderDialogResultSearchUser()}
                <SnackBar visible={this.state.snack_visible}
                          textMessage={this.state.snack_text_message}
                          autoHidingTime={5000}
                />
                {this.makeActionButon()}

            </View>
        )
    }

    onMapReady = () => {
        console.log("MAP READY CALL");
        readUser().then((user) => {
            if (user) {
                this.setState({user: user});
                this.setState({network: user.network, isSaveOneSignalOK: true});

                const myPosition = {
                    latitude: _.isNil(user.latitude) ? 0 : parseFloat(user.latitude),
                    longitude: _.isNil(user.longitude) ? 0 : parseFloat(user.longitude)
                }
                this.setState({myPosition});
                this.refocusMap(false);

                if (user.category) {
                    this.setState({loadingDialog: false});
                    if (user.category !== "geolocated") {
                        this.showMyMembers();
                    } else {
                        if (myPosition.latitude <= 0 && myPosition.longitude <= 0) {
                            this.props.navigation.push(route.updateinfo);
                        }
                    }
                } else {
                    if (Platform.OS === 'android') {
                        this.requestCameraPermission();
                    } else {
                        this.getPosition();
                        this.watchLocation();
                    }
                }
            }
        })
            .catch((error) => {
               // console.log("ERROR LOADING USER", error.message);
            });
    }

    renderTutoOldHome() {
        return (<View style={{flex: 1}}>

            <CopilotStep text="This is a hello world example!" order={1} name="hello">
                {this.makeCardSearch()}
            </CopilotStep>
        </View>)
    }

    render() {
        if (false) {
            return this.renderBottomHome()
        } else
            return this.renderOldHome()
    }

    renderCurrentMarker() {
        if (this.state.currentMarker) {
            return (<View style={{height: 200, backgroundColor: '#fff'}}>
                {this.makeMarkerInformation()}
            </View>)
        }
    }

    makeDialogLoader() {

        return (<ProgressDialog
            visible={this.state.showProgress}
            title={I18n.t("LOADING_PROGRESS")}
            message={I18n.t("WAITING_LONG")}
            animationType="slide"
            activityIndicatorSize="large"
            activityIndicatorColor="blue"
        />)
    }

    showMynetworkMap(usr = null) {
        const user = usr === null ? this.state.user : usr
        let {myNetwork} = this.state;

        this.setState({
            filternetwork: myNetwork,
            page: 0,
            increasePas: 0,
            filternetworkTemp: myNetwork,
            loadingDialog: true
        })
        return new Promise(() => {
            if (myNetwork !== undefined) {
                this.loadingMarkers(this.state.myPosition, myNetwork, this.state.value).then((data) => {

                    let items = data ? data : []
                    this.setState({loadingDialog: false})
                    if (user.category !== undefined && user.category !== null) {
                        const filter = items.filter(item => item.code_parrain === user.code_membre)
                        this.treatNewData(this.state.myPosition, filter, true)
                    } else
                        this.treatNewData(this.state.myPosition, items, true)

                }).catch((e) => {
                    this.setState({loadingDialog: false})

                    console.log("error j")
                    console.log(e)
                })
            } else {
                this.setState({loadingDialog: false})
                console.log("error no net")
            }
        })


    }

    showMyMembers() {
        let {code_membre} = this.state.user;
        if (code_membre !== undefined) {
            loadGroupeAgent(code_membre).then((data) => {
                if (data.success === 1)
                    return this.setState({markers: data.datas})
            })
        } else console.log("error")

    }

    slidingComplete(itemSelected) {
        this.setState({value: this.filterOptions[itemSelected].value, valuePosition: itemSelected});

    }

    makeDistanceDialog() {
        return (<MaterialDialog
            visible={this.state.dialogSliderVisible}
            title={I18n.t('MENU_FILTER')}
            onOk={() => {
                this.setState({dialogSliderVisible: false, showProgress: true})
                setTimeout(() => this.filterPoint(), 300)
            }
            }
            cancelLabel={I18n.t("QUIT_")}
            okLabel={I18n.t('FILTER')}
            onCancel={() => {
                this.setState({dialogSliderVisible: false})
            }}
            onTouchOutside={() => this.setState({dialogSliderVisible: false})}>
            <Text>{I18n.t('TEXT_FILTER_DISTANCE')} </Text>

            <SnapSlider
                items={this.filterOptions}
                defaultItem={this.state.valuePosition}
                labelPosition="bottom"
                onSlidingComplete={(item) => this.slidingComplete(item)}
            />
            <Text>
                <Text style={{fontWeight: "bold"}}>
                    {(this.state.value === undefined ? 0 : this.state.value)}</Text> km {I18n.t("DISTANCE_ARROUND")}
            </Text>

        </MaterialDialog>)
    }

    showFilterDialog() {
        this.setState({dialogSliderVisible: true})
    }

    async filterPoint() {
        const {value, myPosition, user, filternetwork} = this.state
        if (value !== undefined) {
            this.setState({page: 0})
            const metervalue = value * 1000
            let res = this.state.networks.filter(function (item) {
                return item.id === filternetwork.id
            })
            let reseau = res[0];
            this.loadingMarkers(myPosition, filternetwork, value, undefined, true).then((datas) => {
                this.treatNewData(this.state.prevRegion, datas, true)
            }).catch((e) => {
                this.setState({showProgress: false})
                Alert.alert(I18n.t("ERROR_FILTER"), I18n.t("ERROR_FILTER_TEXT"), [{text: I18n.t("CANCEL")}, {
                    text: I18n.t("RESTART"),
                    onPress: () => {
                        this.filterPoint()
                    }
                }])
            })
        } else {
            this.setState({showProgress: false})
            this.setState({
                snack_visible: true, snack_text_message: "impossible de filtrer les élements"
            })
            setTimeout(() => {
                this.setState({snack_visible: false})
            }, 5000)
        }
    }

    userChangeMarker(item) {
       // console.log("Item", item);
        if (this.mapRef !== null && this.mapRef !== undefined) {
            const reg = {
                latitude: parseFloat(item.latitude),
                longitude: parseFloat(item.longitude),
                latitudeDelta: 0.03,
                longitudeDelta: 0.01,
            }
            this.mapRef.animateToCoordinate({
                latitude: parseFloat(item.latitude),
                longitude: parseFloat(item.longitude)
            }, 1000)
            this.mapRef.animateToRegion(reg, 1000);
        }
    }

    geoLocatedAction() {
        return (<ActionButton
            buttonColor={theme.accent}
        >
            <ActionButton.Item buttonColor='#3498db' title={I18n.t("REPOSITIONNING")} onPress={() => this.refocusMap()}
                               size={48}
            >
                <Icon name="person-pin" style={styles.actionButtonIcon}/>
            </ActionButton.Item>

            <ActionButton.Item buttonColor={theme.primary} title={I18n.t("CHANGE_MAP")}
                               onPress={() => {
                                   this.onMapTypeChange();
                               }
                               }
                               size={48}
            >
                <Icon name="layers" style={styles.actionButtonIcon}/>
            </ActionButton.Item>
        </ActionButton>)
    }

    makeNetworkChangeDialog() {
        return (
            <MaterialDialog
                title={I18n.t("CHOICE_NETWORK")}
                visible={this.state.dialogNetworkVisible}
                subtitle={I18n.t("CHOICE_NETWORK_TEXT")}
                onCancel={() => this.setState({dialogNetworkVisible: false})}
                onOk={result => {

                    this.setState({dialogNetworkVisible: false, page: 0});
                    this.setState({showProgress: true, filternetwork: this.state.filternetworkTemp})
                    setTimeout(() => this.showFilterNetwork()
                        , 500)
                }}
            >
                <FlatList style={{height: responsiveHeight(40)}}
                          data={this.state.networks}
                          renderItem={({item}) => this.renderRow(item)}/>
            </MaterialDialog>)

    }


    renderDialogQRCodeScanner() {
        return (
            <Dialog.Container contentStyle={{width: responsiveWidth(80)}} useNativeDriver={true}
                              visible={this.state.showQRCodeScanner}>

                <Dialog.Title>{I18n.t('SCAN')}</Dialog.Title>

                <ScrollView style={[styles.blockView, {borderBottomColor: Color.borderColor, maxHeight: 300}]}>
                    <Text>
                        {I18n.t('BRING_YOUR_CAMERA_CLOSER_TO_SCAN_QR_CODE')}
                    </Text>
                    <QRCodeScanner
                        onRead={(result) => {
                            this.setState({
                                showQRCodeScanner: false
                            });
                            this.props.getQRCodeDetailAction(result.data);
                            //fetchGetUserByIdQRCode(result.data);
                        }}
                        flashMode={RNCamera.Constants.FlashMode.off}
                    />
                </ScrollView>

                <Dialog.Button bold={true} label={I18n.t('CLOSE')} onPress={() => {
                    this.setState({
                        showQRCodeScanner: false
                    });
                }}/>
            </Dialog.Container>
        )
    }

    renderSearchUser() {
        return (
            <MaterialDialog
                title={I18n.t("SEARCH")}
                visible={this.state.dialogSearchUser}
                onCancel={() => this.setState({dialogSearchUser: false})}
                onOk={result => {
                    if (this.state.isPhoneAssureSearch) {
                        this.props.searchUserAction({
                            dial_code: this.state.indicatif,
                            phone: this.state.userName,

                        }, true);
                    } else {
                        this.props.searchUserAction({
                            dial_code: this.state.indicatif,
                            name: this.state.userName,
                        }, true);
                    }

                    this.setState({dialogSearchUser: false});

                }}
            >
                <View>
                    <TextInput
                        style={{
                            marginTop: 10,
                            width: responsiveWidth(90),
                            height: 46,
                            borderRadius: 5,
                            borderWidth: 1,
                            borderColor: "#ccc"
                        }}
                        placeholder={this.state.isPhoneAssureSearch ? I18n.t('PHONE') : I18n.t('NAME')}
                        value={this.state.userName}
                        keyboardType={this.state.isPhoneAssureSearch ? 'numeric' : 'default'}
                        onChangeText={(userName) => {
                            this.setState({userName});
                        }}
                        icon={
                            <FontAwesome
                                style={{zIndex: 10}}
                                name={this.state.isPhoneAssureSearch ? 'phone' : 'user'}
                                size={20}
                            />
                        }
                    />

                    <View style={{
                        flexDirection: 'row',
                        position: 'absolute',
                        top: 22,
                        right: 70,
                        justifyContent: 'space-between',
                        width: 50
                    }}>
                        <FontAwesomeIcon
                            style={{paddingRight: 20}}
                            name='phone'
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                this.setState({
                                    isNumeroAssureSearch: false,
                                    isPhoneAssureSearch: true
                                });
                            }}
                        />
                        <FontAwesomeIcon
                            style={{paddingRight: 20}}
                            name='user'
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                this.setState({
                                    isNumeroAssureSearch: false,
                                    isPhoneAssureSearch: false
                                });
                            }}
                        />
                        <FontAwesomeIcon
                            style={{paddingRight: 20}}
                            name="qrcode"
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                this.setState({
                                    showQRCodeScanner: true
                                });
                            }}
                        />
                    </View>
                </View>

                {/*                    <Fumi iconClass={FontAwesomeIcon}
                          label={I18n.t('NAME')}
                          iconColor={'#f95a25'}
                          iconSize={20}
                          iconName={"user"}
                          value={this.state.userName}
                          onChangeText={(userName) => {
                              this.setState({userName});
                          }}
                          style={styles.input}
                    >
                    </Fumi>*/}

            </MaterialDialog>)

    }

    renderDialogResultSearchUser() {

        const {resultSearchUserByName, errorGetAvisImposition} = this.props;
        console.log("resultGetAvisImposition", resultSearchUserByName);
        return (
            <Dialog.Container contentStyle={{width: responsiveWidth(80)}} useNativeDriver={true}
                              visible={this.state.displayDialogResultSearch}>

                <Dialog.Title>{I18n.t('USAGER_SEARCH')}</Dialog.Title>

                <ScrollView style={[styles.blockView, {borderBottomColor: Color.borderColor, maxHeight: 300}]}>
                    {
                        Array.isArray(resultSearchUserByName.response) && (resultSearchUserByName.response.length) > 0 ?

                            resultSearchUserByName.response.map((item) => (
                                <TouchableOpacity onPress={() => {
                                    this.props.searchUserReset();
                                    this.setState({
                                        userName: '',
                                        displayDialogResultSearch: false
                                    });
                                    console.log("Markers", this.state.markers);

                                    if (this.state.markers.filter((marker) => marker.phone === item.phone).length > 0)
                                        this.userChangeMarker(item);
                                    else {
                                        this.setState({
                                            markers: [...this.state.markers, item],
                                        }, () => {
                                            this.userChangeMarker(item);
                                        });
                                        this.setState({currentNetworkSize: this.state.currentNetworkSize + 1})
                                    }
                                }} style={[styles.paymentItem]}>

                                    <View style={{flexDirection: 'column'}}>
                                        <Text style={styles.title}>{item.lastname}</Text>
                                        <Text style={styles.description}>
                                            {`${item.phone} | ${item.email} | ${item.adresse}`}
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            )) :
                            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                                <Text style={Typography.body1}>{I18n.t('NO_USAGER_CORRESPONDING_TO_SEARCH')}</Text>
                            </View>

                    }
                </ScrollView>

                <Dialog.Button bold={true} label={I18n.t('OK')} onPress={() => {
                    this.props.searchUserReset();
                    this.setState({
                        displayDialogResultSearch: false
                    });
                }}/>
            </Dialog.Container>
        );
    }

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

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

    showNewDialogNetwork() {
        this.setState({dialogNetworkVisible: true})
    }

    async showFilterNetwork() {
        const {myPosition, user, filternetwork} = this.state
        if (filternetwork !== undefined) {
            this.setState({showProgress: true})
            this.loadingMarkers(this.state.myPosition, filternetwork, this.state.value, 0, true).then((data) => {
                this.setState({showProgress: false})
                this.treatNewData(myPosition, data, true)
            }).catch((e) => {
                this.setState({
                    snack_visible: true, snack_text_message: "Probleme de connexion"

                })
                console.log(e)
            })
        } else console.log("error no net")


    }

    showBtnItineraire() {
        return (<Button style={{
                backgroundColor: theme.primary,
                width: responsiveWidth(30),
                height: 36,
                borderRadius: 100,
                marginLeft: 5,
                borderColor: "transparent",
                justifyContent: 'center'
            }}
                        onPress={() => {

                            this.setState({needRoad: true, showProgress: true})
                        }}
            >
                <View
                    style={{flexDirection: 'row'}}
                >
                    <Icon
                        name="near-me"
                        size={16}
                        color='white'
                        style={{alignSelf: 'center'}}
                    />
                    <Text
                        style={{fontSize: 15, color: 'white', marginLeft: responsiveWidth(2)}}
                    >{I18n.t("WAY")}</Text></View>
            </Button>
        )
    }

    showBtnClose() {
        return (<Button style={{
                backgroundColor: theme.reddeconnect,
                height: 36,
                width: responsiveWidth(30),
                borderRadius: 100,
                borderColor: "transparent",
                justifyContent: 'center'
            }}
                        onPress={() => {
                            this.setState({needRoad: false, showProgress: false})
                            /*    this.mapRef.animateCamera({
                                    center:{latitude:parseFloat(this.state.currentMarker.latitude),longitude:parseFloat(this.state.currentMarker.longitude)},
                                    center:this.myPosition,
                                    pitch: 0,
                                    heading: 300,
                                    altitude: 10,
                                    zoom: 15},1000)
                         */
                        }
                        }
            >
                <View
                    style={{flexDirection: 'row'}}
                >
                    <Icon
                        name="close"
                        size={16}
                        color='white'
                        style={{alignSelf: 'center'}}
                    />
                    <Text
                        style={{fontSize: 15, color: 'white', marginLeft: responsiveWidth(2)}}
                    >{I18n.t("CANCEL")}</Text></View>
            </Button>
        )
    }

   // markerManager: MarkerManager

    getHypervisorActionButton() {
        return (<ActionButton
            buttonColor={theme.accent}
        >
            <ActionButton.Item buttonColor='#3498db' title={I18n.t("REPOSITIONNING")}
                               onPress={() => this.refocusMap(false)}
                               size={48}
            >
                <Icon name="person-pin" style={styles.actionButtonIcon}/>
            </ActionButton.Item>

            <ActionButton.Item buttonColor={theme.primary} title={I18n.t("CHANGE_MAP")}
                               onPress={() => {
                                   this.onMapTypeChange();
                               }
                               }
                               size={48}
            >

                <Icon name="map" style={styles.actionButtonIcon}/>
            </ActionButton.Item>

        </ActionButton>)
    }

    moveToMarker(item) {
        this.mapRef.animateToCoordinate({
            latitude: parseFloat(item.latitude),
            longitude: parseFloat(item.longitude)
        }, 1000)
        this.setState({textreach: item.lastname, texta: true})
        this.setState({markersearchfilter: []});

        this.onMarkerPress(item)

    }

    refocusMap(zoom = true) {
        if (zoom) {
            if (this.mapRef && this.state.myPosition !== undefined) {
                this.mapRef.animateCamera({
                    center: {
                        latitude: this.state.myPosition.latitude,
                        longitude: this.state.myPosition.longitude
                    },
                    pitch: 0,
                    heading: 0,
                }, 1000)
            }
        } else {
            if (this.mapRef && this.state.myPosition !== undefined) {
                this.mapRef.animateCamera({
                    center: {
                        latitude: this.state.myPosition.latitude,
                        longitude: this.state.myPosition.longitude
                    },
                    pitch: 0,
                    heading: 0,
                    altitude: 5,

                    zoom: 12
                }, 1000)
            }
        }
        if (this.map)
            this.map.focusToUser()

    }

    renderCardSeashItem(item) {
        return (
            <TouchableOpacity
                key={item.id}
                style={{margin: 5}} onPress={() => {
                this.moveToMarker(item)
            }}>
                <Text style={{flex: 1, fontSize: 14, color: "#000"}}>
                    {item.firstname === null ? item.adresse : item.firstname}</Text>
                <Text style={{flex: 1, fontSize: 12}}>{item.lastname}</Text>
                <Text style={{flex: 1, fontSize: 13, alignSelf: 'flex-end', color: theme.accent}}>{item.network}</Text>
            </TouchableOpacity>)
    }

    retrieveAllPoint(dial_code) {
        /*  let markers= this.markerManager.getLocalMarkers()
              console.log( markers.length)
         if(markers.length>0){
             console.debug("load from local")
             for (let p of markers) {
               console.log(`  ${p.lastname}`);
           }
           this.markerManager.close();

           this.setState({allpoint: [], loadingDialog: false})
         }else*/
        getMakersFrom(dial_code).then((data) => {
            new Promise((resolve, reject) => {
                try {
                    const ds = data.datas
                    this.setState({allpoint: ds, loadingDialog: false})

                    resolve(ds)
                } catch (e) {
                    //Crashlytics.log(e.message)
                    console.warn(e.message)
                    reject(new Error(e.message))
                }
            }).then((ds) => {
                //  this.markerManager.insertMarkers(ds).then((res)=>{console.warn(res)})
                this.onLoadMore()
            }).catch((e) => {
                this.setState({loadingDialog: false})
                //Crashlytics.log(e.message)
                console.log("on get marker")

                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.setState({loadingDialog: true})
                                if (dial_code !== null && dial_code !== undefined)
                                    this.retrieveAllPoint(dial_code)
                                else
                                    this.requestCameraPermission()
                            }
                        }

                    ],
                    {cancelable: false}
                )
            })

        }).catch((e) => {
            console.log("on retreive>getmarkers", e.message)

            this.setState({loadingDialog: false})
            if (this.state.allpoint.length <= 0) {
                console.log("no point")
                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: () => {
                                if (this.state.allpoint.length <= 0) {
                                    this.setState({loadingDialog: true})
                                    if (dial_code !== null && dial_code !== undefined)
                                        this.retrieveAllPoint(dial_code)
                                    else
                                        this.requestCameraPermission()
                                }
                            }
                        }

                    ],
                    {cancelable: false}
                )
            }
        })

    }

    showLoadMoreView() {
        if (this.state.isNeedLoadMore)
            return (<View style={{flex: 1, flexDirection: 'row', width: responsiveWidth(90)}}>
                <Button
                    onPress={() => {
                        this.setState({page: this.state.page + 1})
                        this.onLoadMore()
                    }}
                    style={{
                        borderRadius: 48,
                        height: 48,
                        width: 48,
                        backgroundColor: "white",
                        borderColor: "transparent",
                        alignItems: "center",
                        justifyContent: "center"
                    }}>
                    <Icon name={"refresh"}
                          size={32}

                    />
                </Button>
                <View style={{
                    backgroundColor: "#FFFFFFA0", width: responsiveWidth(20), height: 30, borderRadius: 12,
                    justifyContent: 'center',
                    alignItems: 'center',
                    alignSelf: 'center'
                }}>
                    <Text>{(this.state.markers.length === 0 ? this.state.markers.length : (this.state.markers.length))} / {this.state.currentNetworkSize} </Text>
                </View>
            </View>)
    }

    showLoadingMapView() {
        if (this.state.isLoadingMap)
            return (
                <View
                    style={{
                        flexDirection: 'row',
                        margin: 10,
                        width: responsiveWidth(95),
                        backgroundColor: 'white',
                        justifyContent: "center",
                        alignSelf: "center"
                    }}>
                    <Text style={{
                        fontSize: 12,
                        alignSelf: 'center'
                    }}>{I18n.t("LOADING_TEXT_MARKERS") + " " + this.filterOptions[this.state.valuePosition].value + " km " + I18n.t("DISTANCE_ARROUND")}</Text>
                    <ProgressBarAndroid style={{alignSelf: 'center'}}/>
                </View>

            )
    }

    loadingMarkers(myPosition, filternetwork, value, p = undefined, isFilter = false) {
        return new Promise((resolve, reject) => {
            const {allpoint} = this.state;
            console.log("AllPoint", allpoint);
            console.log("Home state", this.state);
            let page = p !== undefined ? p : this.state.page;
            let data = allpoint
                .filter((mark, index) => {
                    const location = {longitude: parseFloat(mark.longitude), latitude: parseFloat(mark.latitude)};
                    return geolib.getDistance(myPosition, location) <= (value * 1000)
                        && mark.network === filternetwork.name
                });
            console.log("Data before comparative", data);

            if (this.state.valuePosition > 1) {
                if (data.length < this.state.markers.length) {
                    data = allpoint
                        .filter((mark, index) => {
                            const location = {
                                longitude: parseFloat(mark.longitude),
                                latitude: parseFloat(mark.latitude)
                            };
                            return geolib.getDistance(myPosition, location) <= (value * 100000)
                                && mark.network === filternetwork.name
                        });
                } else {
                    data = allpoint
                        .filter((mark, index) => {
                            const location = {
                                longitude: parseFloat(mark.longitude),
                                latitude: parseFloat(mark.latitude)
                            };
                            return geolib.getDistance(myPosition, location) <= (value * 10000)
                                && mark.network === filternetwork.name
                        });
                }
            }
            data = data.slice(0, (page + 1) * this.state.pas)
            try {
                const currentNetwork = allpoint
                    .filter((mark, index) => {
                        const location = {longitude: parseFloat(mark.longitude), latitude: parseFloat(mark.latitude)}
                        return geolib.getDistance(myPosition, location) <= (value * 1000)
                            && mark.network === filternetwork.name
                    });
                console.warn("currentNetworkSize 1", this.state.currentNetworkSize);
                console.warn("currentNetworkSize valuePosition 1", this.state.valuePosition);
                if (isFilter) {
                    this.setState({
                        currentNetworkSize: currentNetwork.length,
                        showProgress: false,
                        currentNetworkMarkers: currentNetwork
                    }, () => {
                        console.warn("currentNetworkSize 2", this.state.currentNetworkSize);
                        console.warn("currentNetworkSize valuePosition 2", this.state.valuePosition);
                    });
                } else {
                    this.setState({
                        showProgress: false,
                        currentNetworkMarkers: currentNetwork
                    }, () => {
                        console.warn("currentNetworkSize 3", this.state.currentNetworkSize);
                        console.warn("currentNetworkSize valuePosition 3", this.state.valuePosition);
                    });
                }
            } catch (e) {
                console.debug("after " + e.message)
            }
            if (this.state.user.category !== 'geolocated' && this.state.user.category !== 'super'
                && this.state.user.category !== 'hyper') {
                if (data.length === 0) {
                    this.loadMoreIfHasNoPoint();
                }
            }
            console.debug("data:", data, "value" + value * 1000)
            resolve(data)
        })
    }

    loadMoreIfHasNoPoint = () => {

        /*           Alert.alert(
                       'INFORMATIONS',
                       '' + this.state.increasePas
                       ,
                       [
                            { text: I18n.t("NO"), onPress: () => { } },
                            {
                                 text: I18n.t("YES"), onPress: () => { }
                            }

                       ],
                       { cancelable: false }
                  ); */
        if (this.state.increasePas === this.filterOptions.length - 1) {
            this.setState({
                increasePas: 0,
                snack_visible: true,
                snack_text_message: I18n.t('NO_NETWORK_MARKER'),
                isLoadingMap: false
            })
            setTimeout(() => {
                this.setState({snack_visible: false})
            }, 5000);
        } else {
            if (this.state.increasePas + 1 !== this.filterOptions.length) {
                this.setState({increasePas: this.state.increasePas + 1, isLoadingMap: true}, () => {
                    this.onLoadMore();
                });
            }
        }

    }

    treatNewData(pos, data, isFilter = false) {
        /*
                  this.setState({ isLoadingMap: false }); */
        let items = data;
        console.log("Data received", data);
        if (data.length > 0) {
            let corrent = items;
            if (isFilter)
                this.setState({showProgress: false})

            if (corrent.length > 0) {
                this.setState({markers: corrent, prevRegion: pos});
            }
            if (items.length < this.state.currentNetworkSize) {
                this.setState({isNeedLoadMore: true})
            } else {
                if (isFilter && items.length <= 0) {
                    this.setState({increasePas: 0, showProgress: false}, () => {
                        this.loadMoreIfHasNoPoint();
                    });
                }
                this.setState({isNeedLoadMore: false})

            }
        } else {
            this.setState({showProgress: false, markers: data});
        }
    }

    async treatPosition(myPosition) {
        const myLastPosition = this.state.myPosition;
        console.log("on treatposition")
        if (myPosition.longitude !== myLastPosition.longitude || myPosition.latitude !== myLastPosition.latitude) {
            this.setState({myPosition: myPosition})
            if (this.map) this.map.focusToUser();
            let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]);
            if (Array.isArray(indicatif))
                indicatif = "+" + indicatif[0];
            this.setState({
                indicatif: indicatif,
                enterPhone: indicatif
            });
            this.getNetworks(indicatif);
            /*            getOpenCagePositionInformation(myPosition).then((response) => {
                            if (response) {
                                if (response.results !== undefined) {
                                    if (response.results.length > 0) {

                                        let most = response.results[0]
                                        let {address_components, county, country} = most.components;
                                        let indicatif = callingCodes([myPosition.longitude, myPosition.latitude]);
                                        console.log("OPENCAGE RESPONSE", indicatif);
                                        this.setState({
                                            address: address_components,
                                            textadress: most.formatted,
                                            indicatif: `+${indicatif}`,
                                            enterPhone: `+${indicatif}`,
                                            shortCountry: county,
                                            longCountry: country
                                        });
                                        this.getNetworks(indicatif);
                                    }

                                } else {
                                    console.log("on treat 1")
                                    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.treatPosition(myPosition)
                                                }
                                            }

                                        ],
                                        {cancelable: false}
                                    )
                                }
                            } else {
                                console.log("on treat 2")

                                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.treatPosition(myPosition)
                                            }
                                        }

                                    ],
                                    {cancelable: false}
                                )
                            }
                        }).catch((error) => {
                            //Crashlytics.log(error.message)
                            console.log("on treat 3")
                            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.treatPosition(myPosition)
                                        }
                                    }

                                ],
                                {cancelable: false}
                            )
                        });*/
            const reg = {
                latitude: myPosition.latitude,
                longitude: myPosition.longitude,
                latitudeDelta: 0.03,
                longitudeDelta: 0.01,
            }
            this.setState({myPosition: myPosition, region: reg});
            if (this.mapRef && !this.state.myPositionIsAnimated) {
                this.mapRef.animateCamera({
                    center: myPosition,
                    pitch: 0,
                    heading: 0,
                    altitude: 5,
                    zoom: 13
                }, 1000)
                this.setState({myPositionIsAnimated: true})

            }

        }

    }
}

const mapStateToProps = state => ({
    loading: state.authKeyReducer.loading,
    authKey: state.authKeyReducer.authKey,
    error: state.authKeyReducer.error,

    loadingSaveOneSignal: state.saveOnesignalReducer.loading,
    resultSaveOneSignal: state.saveOnesignalReducer.result,
    errorSaveOneSignal: state.saveOnesignalReducer.error,

    loadingSearchUserByName: state.searchUserReducer.loading,
    resultSearchUserByName: state.searchUserReducer.result,
    errorSearchUserByName: state.searchUserReducer.error,

    loadingGetQRCodeDetail: state.getQRCodeDetailReducer.loading,
    resultGetQRCodeDetail: state.getQRCodeDetailReducer.result,
    errorGetQRCodeDetail: state.getQRCodeDetailReducer.error,
});

const mapDispatchToProps = dispatch => bindActionCreators({
    getAuthApiKey,
    getWalletActivated,
    saveOnesignalIdsAction,
    saveOnesignalIdsReset,

    searchUserAction,
    searchUserReset,

    getQRCodeDetailReset,
    getQRCodeDetailAction
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(Home);


const markerDetails = StyleSheet.create({
    solde: {
        backgroundColor: theme.accent,
        color: "white",
        marginLeft: 10,
        padding: 5,
        fontSize: 9,
        borderRadius: 100,
    },
    title: {
        color: 'black',
        marginLeft: 10,
        flex: 1,
        fontSize: 11,
        fontWeight: 'bold',
    },
    subtitle2: {
        color: 'black',
        marginLeft: 10,
        flex: 1,
        fontSize: 10,
        fontWeight: 'bold',
    },
    subtitle: {
        color: 'black',
        marginLeft: 9,
        fontSize: 9
    },
    otherInformation: {
        marginLeft: 13,
        fontSize: 9
    },
    reseau: {
        marginLeft: 10,
        fontWeight: 'bold',
        color: theme.accent,
        fontSize: 10
    },
    container: {
        flex: 1,
        width: responsiveWidth(95),
        alignSelf: "center",
        paddingTop: responsiveHeight(1),
        marginBottom: responsiveHeight(1),
        backgroundColor: "white",
        justifyContent: 'flex-start'
    }
})

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FFF',
    },

    panelContainer: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
    },
    panel: {
        height: 600,
        padding: 20,
        backgroundColor: '#f7f5eee8',
    },
    header: {
        backgroundColor: '#f7f5eee8',
        shadowColor: '#000000',
        paddingTop: 20,
        borderTopLeftRadius: 20,
        borderTopRightRadius: 20,
    },
    panelHandle: {
        width: 40,
        height: 8,
        borderRadius: 4,
        backgroundColor: '#00000040',
        marginBottom: 10,
    },
    panelTitle: {
        fontSize: 27,
        height: 35,
    },
    panelSubtitle: {
        fontSize: 14,
        color: 'gray',
        height: 30,
        marginBottom: 10,
    },
    panelButton: {
        padding: 20,
        borderRadius: 10,
        backgroundColor: '#318bfb',
        alignItems: 'center',
        marginVertical: 10,
    },
    panelButtonTitle: {
        fontSize: 17,
        fontWeight: 'bold',
        color: 'white',
    },
    fab: {
        position: 'absolute',
        margin: 16,
        right: 0,
        bottom: 0,
    },
    networkname: {
        backgroundColor: theme.primary,
        padding: 5,
        color: "white",
        marginRight: 10,
        fontSize: 10,
        borderRadius: 12,
    },
    myClusterTextStyle: {
        color: "white"
    },
    myClusterStyle: {
        backgroundColor: theme.accent,
        height: 32,
        justifyContent: 'center',
        alignItems: 'center',
        width: 32,
        borderRadius: 16
    },
    rowContainer: {
        height: 52,
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },
    iconContainer: {
        marginRight: 16,
    },
    mapmarker: {
        width: 52,
        height: 52,
    },
    slidingup: {
        backgroundColor: "transparent",
        position: "absolute",
        height: slideHeight,
        bottom: 0,
        left: responsiveWidth(2.5),
        width: responsiveWidth(95),
        zIndex: 1
    },
    panelHeader: {
        height: 120,
        backgroundColor: '#b197fc',
        alignItems: 'center',
        justifyContent: 'center'
    },
    favoriteIcon: {
        left: responsiveWidth(75),
        backgroundColor: theme.primary,
        width: 64,
        justifyContent: 'center',
        alignContent: 'center',
        bottom: -64,
        position: 'absolute',
        height: 64,
        padding: 8,
        zIndex: 1,
        borderRadius: 32,
    },
    hambuger: {
        color: theme.primary,
        borderColor: theme.primary,
        borderWidth: 1,
        alignSelf: 'center',
        padding: 5,
    },
    topBar: {
        position: 'absolute',
        alignSelf: 'center',
        justifyContent: 'center',
        borderRadius: 10,
        alignItems: 'center',
        marginTop: responsiveHeight(4),
        width: responsiveWidth(90),

    },
    searchInput: {
        flex: 1,
        fontSize: 14
    },
    search: {
        width: responsiveWidth(70),
        height: responsiveHeight(10),
        backgroundColor: '#00000000',


    },

    map: {
        width: responsiveWidth(100),
        height: responsiveHeight(100),
    },
    backgroundd_drawer: {
        backgroundColor: '#000',
    },
    cardsearch: {
        width: responsiveWidth(90),
        height: responsiveHeight(10),
        position: 'absolute',
        alignSelf: 'center',
        marginTop: 5,

    },
    actionButtonIcon: {
        fontSize: 20,
        height: 22,

        color: 'white',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});
