package fr.unice.polytech.al.trafficlight.electriccar.utils;

import co.paralleluniverse.spacebase.*;
import co.paralleluniverse.spacebase.queries.RangeQuery;
import fr.unice.polytech.al.trafficlight.utils.TrafficLight;

import java.util.Set;

/**
 * Created by rhoo on 27/01/17.
 */
public class SpatialDatabase {

    SpaceBase<SpatialTrafficLight> spatialDatabase;
    static Set<SpatialTrafficLight> queryResult;

    public SpatialDatabase() {
        spatialDatabase = new SpaceBaseBuilder().setDimensions(2).build("Town-1");
    }

    public String[] getNextTrafficLight(double longitude, double latitude, double range) {
        String[] result = new String[2];
        AABB pos = AABB.create(latitude,latitude,longitude,longitude);
        RangeQuery query = new RangeQuery(pos,range );
        spatialDatabase.query(query,    new SpatialSetVisitor<SpatialTrafficLight>() {
            public void visit(Set<SpatialTrafficLight> result, Set<ElementUpdater<SpatialTrafficLight>> resForUpdate) {
                queryResult = result;
            }
        });
        SpatialTrafficLight res = null;
        for (SpatialTrafficLight t : queryResult) {
            if (res == null) {
                res = t;
            } else if (pos.distanceSquared(t.getAABB()) < pos.distanceSquared(res.getAABB())) {
                res = t;
            }
        }
        if(res == null) {
            result[0] = "None";
            result[1] = "None";
            return result;
        }
        result[0] = res.getId();
        result[1] = res.getCrossroadId();
        return result;
    }

    public void updateTrafficLight(Set<SpatialTrafficLight> trafficLights) {
        int i = 0;
        for(SpatialTrafficLight stl : trafficLights) {
            System.out.println(stl);
            System.out.println(stl.getAABB());
            System.out.println(i++);
            if(i == 11)
                break;
                //spatialDatabase.insert(new SpatialTrafficLight("a","b",5,5),AABB.create(5,5,5,5));
            else
                spatialDatabase.insert(stl, stl.getAABB());
        }
        System.out.println("out");
    }

}

@@ -1682,16 +1682,45 @@
  i = 0;%0A
+        boolean drop = true;%0A
         
@@ -1758,32 +1758,32 @@
 rafficLights) %7B%0A
-
             Syst
@@ -1866,32 +1866,71 @@
     
-System.out.println(i++);
+if(stl.getCrossroadId().equals(%22carrefour_du_casino%22) && i%3C2) %7B
 %0A   
@@ -1942,19 +1942,16 @@
     
-if(i == 11)
+    i++;
 %0A   
@@ -1967,13 +1967,16 @@
     
-break
+continue
 ;%0A  
@@ -1989,96 +1989,9 @@
     
-    //spatialDatabase.insert(new SpatialTrafficLight(%22a%22,%22b%22,5,5),AABB.create(5,5,5,5));
+%7D
 %0A   

Fix bug