#include "WimaController.h"
#include "MissionController.h"

WimaController::WimaController(QObject *parent) :
    QObject             (parent)
  ,_planView            (true)
  ,_visualItems         (new QmlObjectListModel(parent))
{
    connect(this, &WimaController::currentPolygonIndexChanged, this, &WimaController::recalcPolygonInteractivity);
}

void WimaController::setMasterController(PlanMasterController *masterC)
{
    _masterController = masterC;
    emit masterControllerChanged();
}

void WimaController::setMissionController(MissionController *missionC)
{
    _missionController = missionC;
    emit missionControllerChanged();
}

void WimaController::setCurrentPolygonIndex(int index)
{
    if(index >= 0 && index < _visualItems->count() && index != _currentPolygonIndex){
        _currentPolygonIndex = index;

        emit currentPolygonIndexChanged(index);
    }
}

void WimaController::addGlobalMeasurementArea()
{
    WimaGlobalMeasurementPolygon* newPoly = new WimaGlobalMeasurementPolygon(this);
    _visualItems->append(newPoly);
    int newIndex = _visualItems->count()-1;
    _currentPolygonIndex = newIndex;

    emit currentPolygonIndexChanged(newIndex);
    emit visualItemsChanged();
}

void WimaController::removeArea(int index)
{
    if(index > 0 && index < _visualItems->count()){
        _visualItems->removeAt(index);

        emit visualItemsChanged();

        if(_currentPolygonIndex >= _visualItems->count()){
            setCurrentPolygonIndex(_visualItems->count() - 1);
        }else{
            recalcPolygonInteractivity(_currentPolygonIndex);
        }
    }else{
        qWarning("Index out of bounds!");
    }

}

void WimaController::addServiceArea()
{
    resetAllIsCurrentPolygon();
    WimaServicePolygon* newPoly = new WimaServicePolygon(this);
    newPoly->setIsCurrentPolygon(true);
    _visualItems->append(newPoly);

    emit visualItemsChanged();
}

void WimaController::startMission()
{

}

void WimaController::abortMission()
{

}

void WimaController::pauseMission()
{

}

void WimaController::resumeMission()
{

}

void WimaController::saveMission()
{

}

void WimaController::loadMission()
{

}

void WimaController::recalcVehicleCorridor()
{

}

void WimaController::recalcVehicleMeasurementAreas()
{

}

void WimaController::recalcAll()
{

}

void WimaController::recalcPolygonInteractivity(int index)
{
    resetAllIsCurrentPolygon();
    WimaPolygon* interactivePoly = qobject_cast<WimaPolygon*>(_visualItems->get(index));
    interactivePoly->setIsCurrentPolygon(true);
}

void WimaController::resetAllIsCurrentPolygon()
{
    int itemCount = _visualItems->count();
    for (int i = 0; i < itemCount; i++) {
        WimaPolygon* iteratorPoly = qobject_cast<WimaPolygon*>(_visualItems->get(i));
        iteratorPoly->setIsCurrentPolygon(false);
    }
}



