#include "WimaPolyline.h"

WimaPolyline::WimaPolyline(QObject *parent)
    : QObject       (parent)
    , _boundPolygon  (nullptr)
    , _startVertexIndex(0)
    , _endVertexIndex(1)
{
    connect(&_polyline, &QGCMapPolyline::interactiveChanged, this, &WimaPolyline::interactiveChanged);
}

WimaPolyline::WimaPolyline(QGCMapPolyline *polyline, QObject *parent)
    :WimaPolyline(parent)
{
    _polyline = *polyline;
}

void WimaPolyline::bindPolygon(QGCMapPolygon *polygon)
{
    if(polygon != nullptr){
        _boundPolygon = polygon;
        connect(polygon, &QGCMapPolygon::pathChanged, this, &WimaPolyline::recalcPolyline);
    }else{
        qWarning("Invalid Object!");
    }
}

void WimaPolyline::unbindPolygon()
{
    if(_boundPolygon != nullptr){
        disconnect(_boundPolygon, &QGCMapPolygon::pathChanged, this, &WimaPolyline::recalcPolyline);
        _boundPolygon = nullptr;
    }else{
        qWarning("No Object bound!");
    }
}

void WimaPolyline::swapLimits()
{
    int storage         = _startVertexIndex;
    _startVertexIndex   = _endVertexIndex;
    _endVertexIndex     = storage;
}

void WimaPolyline::setInteractive(bool interactive)
{
    _polyline.setInteractive(interactive);
}
void WimaPolyline::setStartVertexIndex(int PolygonVertexIndex)
{
    if(PolygonVertexIndex >= 0 && PolygonVertexIndex < _boundPolygon->count()){
        _startVertexIndex = PolygonVertexIndex;
        recalcPolyline();
    }else{
        qWarning("Index out of bounds!");
    }
}

void WimaPolyline::setEndVertexIndex(int PolygonVertexIndex)
{
    if(PolygonVertexIndex >= 0 && PolygonVertexIndex < _boundPolygon->count()){
        _endVertexIndex = PolygonVertexIndex;
        recalcPolyline();
    }else{
        qWarning("Index out of bounds!");
    }
}

void WimaPolyline::recalcPolyline()
{
    if (_boundPolygon != nullptr && _boundPolygon->count() > 0){
        if (_startVertexIndex >= _boundPolygon->count()){
            _startVertexIndex = 0;
        }
        if (_endVertexIndex >= _boundPolygon->count()){
            _startVertexIndex = _boundPolygon->count()-1;
        }

        _polyline.clear();
        int i = _startVertexIndex;
        while(1){
            _polyline.appendVertex(_boundPolygon->vertexCoordinate(i));
            if (i == _boundPolygon->count()-1){
                i = 0;
            }else if (i == _endVertexIndex) {
                break;
            }
            i++;
        }

        emit polylineChanged();
    }else{
        qWarning("No object bound!");
    }
}


