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.tudarmstadt.maki.simonstrator.api.component.vehicular.api.information.Position;

public class RoadSideUnitInformationHandler {

    private List<Position> _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<Position> getIntersections() {
        if (!_observedAreaSet) {
            return _positions;
        } else {
            List<Position> result = new ArrayList<>();

            for (Position position : _positions) {
                if (_startX <= position.getX() && position.getX() <= _endX && _startY <= position.getY() && position.getY() <= _endY) {
                    result.add(new Position(position.getX() - _startX, position.getY() - _startY, 0, 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 Position(x, y, 0, 0));
                    }
                }
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            throw new UnsupportedOperationException("Unable to read file", e);
        }
    }

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

        _observedAreaSet = true;
    }
}
