#!/usr/bin/env python

import numpy as np
import pyproj

class Waypoint:
    def dms2dd(coordinate : str):
        split = coordinate.split('.')
        if 4 != len(split):
            return 0.0

        direction = split[0][1]
        degrees = float(split[0][1:])
        minutes = float(split[1])
        seconds = float(split[2]) * (float(split[3]) / 1000.0)

        dd = degrees + minutes / 60.0 + seconds / (60 * 60)
        if 'E' == direction or 'S' == direction:
            dd *= -1.0

        return dd

    def coordinateArgument(value):
        if True == isinstance(value, str):
            return Waypoint.dms2dd(value)
        elif True == isinstance(value, (float, int)):
            return float(value)
        else:
            raise Exception('Invalid constructor argument')

    def __init__(self, **kwargs):
        self.Name = None
        self.Coordinate = None
        self.Altitude = None
        self.Speed = None
        self.BaseTurn = False
        self.FinalTurn = False

        latitude = None
        longitude = None
        for key, value in kwargs.items():
            if 'name' == key.lower():
                self.Name = str(value)
            elif 'latitude' == key.lower():
                latitude = Waypoint.coordinateArgument(value)
            elif 'longitude' == key.lower():
                longitude = Waypoint.coordinateArgument(value)
            elif 'altitude' == key.lower():
                self.Altitude = int(value)
            elif 'speed' == key.lower():
                self.Speed = int(value)
            elif 'base' == key:
                self.BaseTurn = bool(value)
            elif 'final' == key:
                self.FinalTurn = bool(value)
            else:
                raise Exception('Invalid constructor argument: ' + key)

        if None != latitude and None != longitude:
            self.Coordinate = np.array([ latitude, longitude ])

    def __str__(self):
        return 'Name: ' + self.Name + ', Lat: ' + str(self.Coordinate[0]) + ', Lon: ' + str(self.Coordinate[1])

    def haversine(self, other):
        geodesic = pyproj.Geod(ellps='WGS84')
        _, _, distance = geodesic.inv(self.Coordinate[1], self.Coordinate[0], other.Coordinate[1], other.Coordinate[0])
        return distance / 1000.0 * 0.539957

    def bearing(self, other):
        geodesic = pyproj.Geod(ellps='WGS84')
        forward, _, _ = geodesic.inv(self.Coordinate[1], self.Coordinate[0], other.Coordinate[1], other.Coordinate[0])
        return forward

    def project(self, bearing, distance):
        geodesic = pyproj.Geod(ellps='WGS84')
        longitude, latitude, _ = geodesic.fwd(self.Coordinate[1], self.Coordinate[0], bearing, distance)
        return np.array([ latitude, longitude ])        
