package seng302.Model;

import javafx.scene.paint.Color;
import seng302.GPSCoordinate;
import seng302.GraphCoordinate;
import seng302.RaceDataSource;
import seng302.RaceMap;

import java.util.List;

/**
 * Created by fwy13 on 4/05/17.
 */
public class ResizableRaceMap extends ResizableCanvas {
    private RaceMap map;
    private final List<GPSCoordinate> raceBoundaries;
    private double[] xpoints = {};
    private double[] ypoints = {};

    public ResizableRaceMap(RaceDataSource raceData){
        super();
        raceBoundaries = raceData.getBoundary();

        double lat1 = raceData.getMapTopLeft().getLatitude();
        double long1 = raceData.getMapTopLeft().getLongitude();
        double lat2 = raceData.getMapBottomRight().getLatitude();
        double long2 = raceData.getMapBottomRight().getLongitude();
        setMap(new RaceMap(lat1, long1, lat2, long2, (int) getWidth(), (int) getHeight()));
        //draw();
    }

    private void setMap(RaceMap map) {
        this.map = map;
    }
    /**
     * Draw boundary of the race.
     */
    private void drawBoundaries() {
        if (this.raceBoundaries == null) {
            return;
        }
        gc.setFill(Color.AQUA);
        setRaceBoundCoordinates();

        gc.setLineWidth(1);
        gc.fillPolygon(xpoints, ypoints, xpoints.length);
    }

    private void setRaceBoundCoordinates() {
        xpoints = new double[this.raceBoundaries.size()];
        ypoints = new double[this.raceBoundaries.size()];
        for (int i = 0; i < raceBoundaries.size(); i++) {
            GraphCoordinate coord = map.convertGPS(raceBoundaries.get(i));
            xpoints[i] = coord.getX();
            ypoints[i] = coord.getY();
        }
    }

    public void draw(){

        double width = getWidth();
        double height = getHeight();

        gc.clearRect(0, 0, width, height);

        if (map == null) {
            return;//TODO this should return a exception in the future
        }
        this.map.setHeight((int) height);
        this.map.setWidth((int) width);

        gc.setLineWidth(2);
        drawBoundaries();
    }

}
