import React, {Component} from 'react';

var db = require('./persistences/db.js');
import I18n from 'react-native-i18n'
import {readUser} from './AuthApi'
import {isDebugMode, MARKER_URL} from "./IlinkConstants";

let GEOCODDING_URL = "https://ilink-app.com:8080/geocode";
let API_KEY = "AIzaSyCQY0rwMM9Pn9XWt5F6YLhGoez_bU1IGtc"


export const getLocalMarkers = () => {
   // return db.markers.get_all()
   return db.markers.get_all()
}
export const getMakersFrom = function (country) {
    let tag = {tag: 'location', type: 'all', country: country}
    return timeout(15000, queryMap(tag))
}

function timeout(ms, promise) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error(I18n.t("TEXT_NETWORK_UNABLE")))
        }, ms)
        promise.then(resolve, reject)
    })
}

export const loadMarkers = (position, reseau, distance, page) => {
    return readUser().then((users) => {
        let user = users;
        if (user !== undefined) {
            let tag = {
                tag: 'location', type: 'around',
                page: page,
                id: user.id, position: position, network: reseau, distance: distance
            }
            return queryMap(tag)
        }
    })

}

export const loadGroupeAgent = (member_code) => {
    let data = {tag: 'location', type: 'all_network', codeparrain: member_code}
    return queryMap(data)
}
export const loadNetwork = (network, userid) => {
    let data = {tag: 'location', type: "all_network_point", id: userid, network: network}
    return queryMap(data)
}
export const getPositionInformation = async (position) => {
    let url = GEOCODDING_URL.concat('?latitude=' + position.latitude + "&longitude=" + position.longitude);
    const data = fetch(url, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
    })
        .then((response) => response.json())
        .then((responseJson) =>
            responseJson
        ).catch((error) => {
            console.log("error get position")
            console.log(error)
        });

    //console.warn("freud", data);
    return data;
}
const queryMap = async (data) => {
    data['lang'] = I18n.currentLocale()
    data["test"] = isDebugMode;
    // console.warn("REQUEST URL QUERY MAP", MARKER_URL);
    // console.warn("REQUEST BODY QUERY MAP", JSON.stringify(data));
    let response = await fetch(MARKER_URL, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),

    });
    let responseText = await response.text()
    //console.log("response= " + responseText)
    try {
        let responseJson = JSON.parse(responseText);
        console.warn("JSON RESPONSE", responseJson);
        console.warn("SERVER RESPONSE SUCCESS", responseText);
        return responseJson;
    } catch (e) {
        //console.log("erreur=" + responseText)
        //console.log(response);
        console.warn("SERVER RESPONSE ERROR", responseText);
        throw new Error("Erreur lors de la conversion en json")
    }
    throw new Error("Erreur lors de la conversion en json")

}
