package de.tud.kom.p2psim.impl.topology.placement;

import de.tud.kom.p2psim.api.topology.TopologyComponent;
import de.tud.kom.p2psim.api.topology.placement.PlacementModel;
import de.tud.kom.p2psim.impl.topology.PositionVector;
import de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.traci.TraciSimulationController;
import de.tudarmstadt.maki.simonstrator.api.EventHandler;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;
import de.tudarmstadt.maki.simonstrator.api.component.vehicular.api.SimulationSetupExtractor;
import de.tudarmstadt.maki.simonstrator.api.util.XMLConfigurableConstructor;

import java.util.List;

public class TrafficLightPlacementModel implements PlacementModel, EventHandler {
    private final String sumoExe;
    private final String sumoConfigFile;

    private final String sumoIntersections;

    private final int offsetX;
    private final int offsetY;
    private final int width;
    private final int height;

    private SimulationSetupExtractor controller;

    private List<Location> intersections;
    private int currentIndex = 0;

    @XMLConfigurableConstructor({ "sumoExe", "sumoConfigFile", "offsetX", "offsetY", "width", "height" })
    public TrafficLightPlacementModel(String sumoExe, String sumoConfigFile, String offsetX, String offsetY, String width, String height) {
        this.sumoExe = sumoExe;
        this.sumoConfigFile = sumoConfigFile;

        this.sumoIntersections = null;

        this.offsetX = Integer.parseInt(offsetX);
        this.offsetY = Integer.parseInt(offsetY);
        this.width = Integer.parseInt(width);
        this.height = Integer.parseInt(height);

        initializeModel();
    }

    protected void initializeModel() {
        if (this.sumoExe != null) {
            controller = TraciSimulationController.createSimulationController(sumoExe, sumoConfigFile, null);
            controller.init();
            controller.setObservedArea(offsetX, offsetY, offsetX + width, offsetY + height);
            intersections = controller.getAllIntersections(true);
        }
    }

    @Override
    public void addComponent(TopologyComponent comp) {

    }

    @Override
    public PositionVector place(TopologyComponent comp) {
        if (currentIndex < intersections.size()) {
            Location intersection = intersections.get(currentIndex);
            currentIndex++;
            return new PositionVector(intersection.getLongitude(), intersection.getLatitude());
        } else {
            return new PositionVector(Double.NaN, Double.NaN);
        }
    }

    @Override
    public void eventOccurred(Object content, int type) {
        
    }
}
