package de.tud.kom.p2psim.impl.topology.movement.vehicular.sumo.simulation.controller.csv;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import de.tud.kom.p2psim.impl.topology.util.PositionVector;
import de.tudarmstadt.maki.simonstrator.api.component.sensor.location.Location;

public class RoadSideUnitInformationHandler {

	private List<Location> _positions = new ArrayList<>();

	private boolean _observedAreaSet = false;
	private double _startX = -1;
	private double _startY = -1;
	private double _endX = -1;
	private double _endY = -1;

	public List<Location> getIntersections() {
		if (!_observedAreaSet) {
			return _positions;
		} else {
			List<Location> result = new ArrayList<>();

			for (Location position : _positions) {
				if (_startX <= position.getLongitudeOrX() && position.getLongitudeOrX() <= _endX && _startY <= position.getLatitudeOrY() && position.getLatitudeOrY() <= _endY) {
					result.add(new PositionVector(position.getLongitudeOrX() - _startX, position.getLatitudeOrY() - _startY, 0));
				}
			}

			return result;
		}
	}

	public void parseIntersectionsFile(String pRoadSideUnitDataPath) {
		File file = new File(pRoadSideUnitDataPath);
		try {
			FileInputStream inputStream = new FileInputStream(file);
			Scanner scanner = new Scanner(inputStream);

			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();

				if (line.contains(";")) {
					String[] split = line.split(";");
					if (split.length == 2) {
						double x = Double.parseDouble(split[0]);
						double y = Double.parseDouble(split[1]);
						_positions.add(new PositionVector(x, y, 0));
					}
				}
			}
			scanner.close();
		} catch (FileNotFoundException e) {
			System.err.println("Unable to read file " + e.getMessage());
		}
	}

	public void setObservedArea(double pStartX, double pStartY, double pEndX, double pEndY) {
		_startX = pStartX;
		_startY = pStartY;
		_endX = pEndX;
		_endY = pEndY;

		_observedAreaSet = true;
	}
}
