#include "GeoUtilities.h"
#include <QtMath>


QGeoCoordinate GeoUtilites::toGeo(const QVector3D &point, const QGeoCoordinate &origin)
{
    double x = point.x();
    double y = point.y();
    double z = point.z();

    double lat = origin.latitude()/180*M_PI;
    double lon = origin.longitude()/180*M_PI;
    double h   = origin.altitude();

    if (!qFuzzyCompare(lat, M_PI_2)) // this could (unlikely) be a problem, replace with different coordinate transformation
        return QGeoCoordinate(/* lat */ qAtan(x/cos(lat)/earthRadius) + lon,
                              /* lon */ qAtan(y/earthRadius) + lat,
                              /* alt */ h + z);
    else
        return QGeoCoordinate(); // singularity occurred (1/cos(pi/2) = inf)
}

QVector3D GeoUtilites::toCartesian(const QGeoCoordinate &point, const QGeoCoordinate &origin)
{
    double lat = point.latitude()/180*M_PI;
    double lon = point.longitude()/180*M_PI;
    double h   = point.altitude();

    double latO = origin.latitude()/180*M_PI;
    double lonO = origin.longitude()/180*M_PI;
    double hO   = origin.altitude();

    double dlon = lon-lonO;
    double dlat = lat-latO;


    if (!qFuzzyCompare(dlon, M_PI_2) && !qFuzzyCompare(dlat, M_PI_2))
        return QVector3D(/* x */ qTan(dlon)*earthRadius*qCos(latO),
                         /* y */ qTan(dlat)*earthRadius,
                         /* z */ h - hO);
    else
        return QVector3D(); // singularity occurred (tan(pi/2) = inf)

}

GeoUtilites::QGeoList GeoUtilites::toGeo(const GeoUtilites::QVector3DFList &points, const QGeoCoordinate &origin)
{
    GeoUtilites::QGeoList coordinates;
    for (auto point : points)
        coordinates.append(toGeo(point, origin));

    return coordinates;
}

GeoUtilites::QVector3DFList GeoUtilites::toCartesian(const GeoUtilites::QGeoList &coordinates, const QGeoCoordinate &origin)
{
    GeoUtilites::QVector3DFList points;
    for (auto coordinate : coordinates )
        points.append(toCartesian(coordinate, origin));

    return points;
}
