import React from 'react';
import I18n from 'react-native-i18n'
import {db} from './persistences/db';
import {
    adhesionUrl,
    configActionUrl,
    isDebugMode,
    locationActionUrl,
    memberActionUrl,
    networkActionUrl
} from "./IlinkConstants"

var DBEvents = require('react-native-db-models').DBEvents;
var serializeJSON = function (data) {

    return Object.keys(data).map(function (keyName) {
        return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
    }).join('&');

};


export const getCodeInformation = (code) => {
    var data = {
        "tag": 'member', "type": "agen_info_code", "code": code,
        "lang": I18n.currentLocale()
    };

    return queryData(data, memberActionUrl)
}
export const getPubActiveObject = (idcpuntry) => {
    return queryData({"tag": "get_pub", "id_country": idcpuntry}, configActionUrl);

}
export const getPasObject = () => {
    return queryData({"tag": "get_pas"}, configActionUrl);
}

function queryAuth(data) {
    return timeout(50000, queryData(data, adhesionUrl))
}

async function queryData(data, url) {
    console.warn("REQUEST URL", url);
    console.warn("REQUEST BODY", JSON.stringify(data));
    data["lang"] = I18n.currentLocale();
    data["isTest"] = isDebugMode
    /*    await axios({
            url,
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            data: JSON.stringify(data),
        }).then(serverResponse => {
            console.warn("SERVER RESPONSE SUCCESS", serverResponse);
            return serverResponse.data;
        }).catch(error => {
            console.warn("SERVER RESPONSE ERROR", error);
            return {"error": "error", "error_msg": error}
        });*/

    let response = await fetch(url, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    });
    let responseJson = null;
    let responseText = await response.text()
    try {
        console.warn("SERVER RESPONSE SUCCESS", responseText);
        responseJson = JSON.parse(responseText)
    } catch (e) {
        console.warn("SERVER RESPONSE ERROR", responseText);
        return {"error": "error", "error_msg": responseText}
    }
    return responseJson;


}

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 validateUser = (user) => {
    var data = {
        "tag": 'member', "type": "valider_simple", "phone": user.phone,
        "lang": I18n.currentLocale()
    };
    return queryData(data, memberActionUrl)
};
export const updatePosition = async (longitude, latitude) => {
    const user = await readUser()
    const data = {
        'tag': 'member',
        'type': 'update_position',
        "agentId": user['agentId'],
        "longitude": longitude,
        latitude: latitude
    }
    return queryData(data, memberActionUrl)
}
export const valifateAgent = (user, info) => {
    var data = info;
    if (data === null) data = {}
    data["tag"] = "member";
    data['type'] = "validate_agent";
    data["phone"] = user.phone;
    data['code_validation'] = user.validation_code;
    if (user.category === "super" && (info === null || (info !== null && (info.nbre_code === undefined || info.nbr_code === null)))) {
        data["nbre_code"] = 10;
        data["nbre_code_superviseur"] = 0
    } else if (info === null || (info !== null && (info.nbre_code === undefined || info.nbre_code === null))) {
        data["nbre_code"] = 0;
        data["nbre_code_superviseur"] = 0
    }
    console.log(data);

    return queryData(data, memberActionUrl)
}

export const disconnect = () => {
    return new Promise((resolve, reject) => {
        readBrutUser().then((user) => {
            db.remove({"_id": user._id}, {multi: true}, (error, numRemoved) => {
                if (error !== null) {
                    reject(error)
                } else {
                    console.log(numRemoved)
                    if (numRemoved > 0) {
                        resolve()
                    }
                }
            })
        })
    })
}

export const login = (phone: String, password: String, type: Number) => {
    console.log("CURRENT_LANG", I18n.currentLocale());
    var data = {
        tag: type === 0 ? "login_user" : "login_agent",
        phone: phone,
        password: password,
        lang: I18n.currentLocale()
    };

    return queryAuth(data);
};

export const reinitpassword = ($phone, $type) => {
    var data = {"tag": "forgot_pass", "number": $phone, "typeaccount": $type, "lang": I18n.currentLocale()};
    return queryAuth(data)
}
export const updateUserData = async (data) => {
    const user = await readUser()
    user.longitude = data.longitude
    user.latitude = data.latitude
    db.update({"user": {$exists: true}}, {user: user}, {}, function (err, numReplaced) {
        console.warn(err, numReplaced)
    })
    /*  new Promise((resolve,reject)=>{
          readBrutUser().then((user)=>{
              db.remove({"_id": user._id},{multi:true},(error,numRemoved)=>{
                  if(error!==null){
                      reject(error)
                  }else {
                      let muser=user

                      db.insert(muser, function(err){
                          if(err!==null) {
                              console.log("error when save user")
                              console.log(err)
                          }

                      })
                      console.log(numRemoved)
                      if (numRemoved > 0) {
                          resolve()
                      }
                  }
              })
          })
      })*/

}
export const saveNewuser = (muser) => {
    let user = {
        user: muser
    }
    db.insert(user, function (err) {
        if (err !== null) {
            console.log("error when save user")
            console.log(err)
        }

    })
}

const readBrutUser = () => {
    return new Promise((resolve, reject) => {
        db.findOne({"user": {$exists: true}}, (err, result) => {
            if (err !== null || result === null || result.user === undefined) {
                resolve(null)
            } else {
                if (result.user === null) {
                    resolve(null)
                } else
                    resolve(result)
            }
            ;
        })
    });
}

export const readUser = () => {
    return new Promise((resolve, reject) => {
        db.findOne({"user": {$exists: true}}, async (err, result) => {
            if (err !== null || result === null || result.user === undefined) {
                resolve(null)
            } else {
                if (result.user === null) {
                    resolve(null)
                } else {

                    resolve(result.user)
                }
            }
        })
    });
}

export const createGeolocatedAccount = (user) => {

    return queryData(user, memberActionUrl)
}
export const createUserAccount = (user) => {
    return queryData(user, memberActionUrl)
}

export const acceptDemandAdhesion = (data) => {
    return queryData({
        "tag": "member",
        "type": "activeSupervisor",
        "code": data.code_membre,
        "phone": data.phone
    }, memberActionUrl)
}
export const deleteUser = async (data) => {
    return queryData({
        "tag": "member",
        "type": "deleteAgent",
        "code": data.code_membre,
        "phone": data.phone
    }, memberActionUrl)
}
export const listDemandAdhesion = async () => {
    const user = await readUser();
    const items = await queryData({
        "type": "list_demande_adhesion",
        "tag": "member",
        "codeparrain": user.code_membre
    }, memberActionUrl)
    return items;
}
export const categoryChild = async (code) => {
    const codes = await queryData({"type": "get_category_child", "tag": "member", "codeparrain": code}, memberActionUrl)

    return codes;
}
export const getListCountriesActive = async () => {
    const countries = await queryData({"tag": "avail_countries"}, networkActionUrl);
    return countries;

}
export const getCountryNetwork = (country) => {
    console.warn(country)
    return queryData({"tag": 'listnetworkscountryindicatif', 'indicatif': country}, networkActionUrl)
}
export const getTownInformationName = (town) => {
    return queryData({"tag": "town_information_name", "name": town}, locationActionUrl);
}
export const generateAgentGeo = async (newPhone) => {
    const user = await readUser();
    const items = await queryData({
        "type": "generateNetworkAgentForGeo",
        "tag": "member",
        "code_parrain": user.code_membre,
        'phone': newPhon
    }, memberActionUrl)
    return items;
}
export const AssignAgentGeo = async (codeValidation, phone, provider_class) => {
    const user = await readUser();
    const items = await queryData({
        "type": "assignNetworkAgentToGeo",
        "tag": "member",
        "agentId": user.agentId,
        'code_parrain': codeValidation,
        "phone": phone,
        "provider_class_id": provider_class
    }, memberActionUrl)
    return items;
}
