package seng302.Model;

import org.geotools.referencing.GeodeticCalculator;
import seng302.GPSCoordinate;

import java.awt.geom.Point2D;

/**
 * Created by esa46 on 29/03/17.
 */
public class Marker {
    private final GPSCoordinate averageGPSCoordinate;
    private GPSCoordinate mark1;
    private GPSCoordinate mark2;
    private final int sourceId1;
    private final int sourceId2;

    public Marker(GPSCoordinate mark1, int sourceId) {
        this(mark1, mark1, sourceId, sourceId);
    }

    public Marker(GPSCoordinate mark1, GPSCoordinate mark2, int sourceId1, int sourceId2) {

        this.mark1 = mark1;
        this.mark2 = mark2;
        this.averageGPSCoordinate = calculateAverage();
        this.sourceId1 = sourceId1;
        this.sourceId2 = sourceId2;

    }

    /**
     *
     * @param mark1 Mark coordinates.
     */
    public Marker(GPSCoordinate mark1) {
        this(mark1, mark1, 0,0);
    }

    /**
     *
     * @param mark1 Mark one coordinate
     * @param mark2 Mark two coordinate
     */
    public Marker(GPSCoordinate mark1, GPSCoordinate mark2) {
        this(mark1, mark2, 0,0);
    }

    public GPSCoordinate getMark1() {
        return mark1;
    }

    public GPSCoordinate getMark2() {
        return mark2;
    }

    /**
     * Returns true if mark consists of two points, e.g. it is a gate.
     * @return boolean
     */
    public boolean isCompoundMark() {
        return mark1 != mark2;
    }

    public GPSCoordinate getAverageGPSCoordinate() {
        return averageGPSCoordinate;
    }


    private GPSCoordinate calculateAverage() {

        GeodeticCalculator calc = new GeodeticCalculator();
        calc.setStartingGeographicPoint(mark1.getLongitude(), mark1.getLatitude());
        calc.setDestinationGeographicPoint(mark2.getLongitude(), mark2.getLatitude());
        double azimuth = calc.getAzimuth();
        double distance = calc.getOrthodromicDistance();

        GeodeticCalculator middleCalc = new GeodeticCalculator();
        middleCalc.setStartingGeographicPoint(mark1.getLongitude(), mark1.getLatitude());
        middleCalc.setDirection(azimuth, distance / 2);
        Point2D middlePoint = middleCalc.getDestinationGeographicPoint();
        return new GPSCoordinate(middlePoint.getY(), middlePoint.getX());

    }

    public void setCurrentPosition1(GPSCoordinate gpsCoordinate){
        mark1 = gpsCoordinate;
    }

    public void setCurrentPosition2(GPSCoordinate gpsCoordinate){
        mark2 = gpsCoordinate;
    }

    public int getSourceId1() {
        return sourceId1;
    }

    public int getSourceId2() {
        return sourceId2;
    }
}
