#include "WimaControllerDetail.h"
#include <QGeoCoordinate>


SnakeWorker::SnakeWorker(QObject *parent) : QThread(parent)
  , _lineDistance       (3) // meter
  , _minTransectLength  (2) // meter
{

}

void SnakeWorker::setScenario(const Scenario &scenario)
{
    _scenario = scenario;
}

void SnakeWorker::setProgress(const QList<int> &progress)
{
    _progress.clear();
    for (auto p : progress) {
        assert(p >= -1 && p <= 100);
        _progress.push_back(p);
    }
}

void SnakeWorker::setLineDistance(double lineDistance)
{
    assert(lineDistance > 0);
    _lineDistance = lineDistance;
}

void SnakeWorker::setMinTransectLength(double minTransectLength)
{
    assert(minTransectLength > 0);
    _minTransectLength = minTransectLength;
}

const WorkerResult_t &SnakeWorker::getResult() const
{
    return _result;
}

void SnakeWorker::run()
{
    // Reset _result struct.
    _result.success = false;
    _result.errorMessage = "";
    _result.waypoints.clear();
    _result.returnPathIdx.clear();
    _result.arrivalPathIdx.clear();

    FlightPlan flightplan;
    flightplan.setScenario(_scenario);
    flightplan.setProgress(_progress);

    // Trying to generate flight plan.
    if ( !flightplan.generate(_lineDistance, _minTransectLength) ){
        // error
        for (auto c : flightplan.errorString){
            _result.errorMessage.push_back(QChar(c));
        }
    } else {
        //success!!!
        _result.success = true;

        // Fill result struct.
        auto waypoints = flightplan.getWaypoints();
        for (auto vertex : waypoints){
            _result.waypoints.append(QVariant::fromValue(QGeoCoordinate(vertex[0], vertex[1], 0)));
        }

        auto arrivalPathIdx = flightplan.getArrivalPathIdx();
        for (auto idx : arrivalPathIdx){
            _result.arrivalPathIdx.append(idx);
        }

        auto returnPathIdx = flightplan.getReturnPathIdx();
        for (auto idx : returnPathIdx){
            _result.returnPathIdx.append(idx);
        }

    }

    emit resultReady();
}
