#include "WimaArea.h"

WimaArea::WimaArea(QObject *parent) :
    WimaArea           (nullptr, parent)
{
    //qWarning() << "WimaPolygon:: polygon count" << _polygon->count();
}

WimaArea::WimaArea(WimaArea *other, QObject *parent):
    QGCMapPolygon (parent)
    ,_maxAltitude             (30)
    ,_wimaVehicle             (new WimaVehicle(this))
{
    if (other != nullptr) {
        _maxAltitude = other->maxAltitude();
        _wimaVehicle = other->vehicle();
        setPath        (other->path());
        setCenter      (other->center());
        setCenterDrag  (other->centerDrag());
        setInteractive (other->interactive());
    }

}

WimaArea::~WimaArea()
{

}


void WimaArea::setMaxAltitude(double alt)
{
    if(alt > 0 && alt != _maxAltitude){
        _maxAltitude = alt;
        emit maxAltitudeChanged();
    }
}


void WimaArea::setVehicle(WimaVehicle *vehicle)
{
    if(_wimaVehicle != vehicle){
        _wimaVehicle->deleteLater();
        _wimaVehicle =  vehicle;
        emit vehicleChanged();
    }
}

/*QList<WimaArea *>* WimaArea::splitArea<T>(WimaArea *polygonToSplitt, int numberOfFractions)
{
    if(numberOfFractions > 0 && polygonToSplitt != nullptr){
        WimaArea* poly;
        if(p)
        = new WimaArea(polygonToSplitt, this);
        QList<WimaArea*>* list = new QList<WimaArea*>();
        list->append(poly);
        return list;
    }
    return nullptr;
}


QList<QGCMapPolygon*>* WimaArea::splitArea(int numberOfFractions)
{
    return splitPolygonArea(this, numberOfFractions);
}*/

int WimaArea::getClosestVertexIndex(QGeoCoordinate coordinate)
{
    if (this->count() == 0) {
        qWarning("Polygon count == 0!");
        return -1;
    }else if (this->count() == 1) {
        return 0;
    }else {
        int index = 0;
        double min_dist = coordinate.distanceTo(this->vertexCoordinate(index));
        for(int i = 1; i < this->count(); i++){
            double dist = coordinate.distanceTo(this->vertexCoordinate(i));
            if (dist < min_dist){
                min_dist = dist;
                index = i;
            }
        }

        return index;
    }
}

QGeoCoordinate WimaArea::getClosestVertex(QGeoCoordinate coordinate)
{
    return this->vertexCoordinate(getClosestVertexIndex(coordinate));
}

QGCMapPolygon* WimaArea::toQGCPolygon(WimaArea *poly)
{
    if (poly != nullptr) {
        QGCMapPolygon* qgcPoly = new QGCMapPolygon(this);
        qgcPoly->setPath(poly->path());
        qgcPoly->setCenter(poly->center());
        qgcPoly->setCenterDrag(poly->centerDrag());
        qgcPoly->setInteractive(poly->interactive());

        return qgcPoly;
    } else {
        qWarning("WimaArea::toQGCPolygon(): poly == nullptr");
        return nullptr;
    }
}

QGCMapPolygon *WimaArea::joinPolygons(QList<QGCMapPolygon *> polyList)
{

}


