const Realm = require('realm');
let geolib = require("geolib")

import GeolocatedPoint from './../../model/GeolocatedPoint'
import Network from './../../model/Network'
import {getLocalMarkers} from '../MapService';

GeolocatedPointSchema = {
    name: "GeolocatedPoint",
    properties: {
        id: 'int',
        firstname: 'string?',
        lastname: 'string',
        adresse: 'string',
        longitude: 'float',
        latitude: 'float',
        phone: 'string?',
        solde: 'int',
        country: 'string',
        category: 'string',
        email: 'string',
        etat: 'int',
        code_parrain: 'string',
        code_dial: 'string',
        network_id: 'int',
        transactionNumber: 'string?',
        code_membre: 'string',
        network: 'string'
    }
}
export default class MarkerManager {
    realm

    constructor() {
        this.realm = new Realm({schema: [GeolocatedPointSchema]})
    }

    getLocalMarkers() {
        return this.realm.objects('GeolocatedPoint').slice(0, 3);
    }

    async getLocalMarkersFromDistance(distance: 5, location) {
        return new Promise((resolve, reject) => {
            let points = getLocalMarkers();
            return points.filter((mark, index) => {
                const position = {longitude: parseFloat(mark.longitude), latitude: parseFloat(mark.latitude)}
                return geolib.getDistance(position, location) <= (distance * 1000)
            })
        });
    }

    close() {
        this.realm.close();
    }

    async insertMarkers(markers: Array<any>) {
        return new Promise((resolve, reject) => {
            var count = 0
            let rejet = []
            markers.forEach((value, index) => {
                try {

                    this.realm.write(() => {
                        this.realm.create('GeolocatedPoint', value);
                    });
                    count++
                } catch (e) {
                    console.log("Error on creation");
                    reject(e)
                    rejet.push(value)
                }
            })

            resolve({row: count, total: markers.length, rejet: rejet})

        })


    }
}
