#include "WimaPolygonContainer.h"

WimaPolygonContainer::WimaPolygonContainer(QObject *parent) :
    QObject             (parent)
    ,_flatListDirty     (true)
{
    connect(this, &WimaPolygonContainer::itemListChanged, this, &WimaPolygonContainer::setFlatListDirty);
}

QList<WimaPolygon *> &WimaPolygonContainer::returnItems()
{
    return _itemList;
}

void WimaPolygonContainer::addItem(WimaPolygon *polygon)
{
    if(polygon != nullptr){
        _itemList.append(polygon);

        emit itemListChanged();
    }
    else {
        qWarning("Not a valid WimaPolygon!");
    }
}

void WimaPolygonContainer::removeItem(int itemIndex)
{
    if(itemIndex >= 0 && itemIndex < _itemList.count()){
        _itemList.removeAt(itemIndex);

        emit itemListChanged();
    }else {
        qWarning("Invalid item Index. Index must be in 0..%i.", _itemList.count()-1);
    }
}

void WimaPolygonContainer::removeItem(WimaPolygon *polygon)
{
    if(polygon != nullptr){
        _itemList.removeOne(polygon);

        emit itemListChanged();
    }
    else {
        qWarning("Not a valid WimaPolygon!");
    }
}

QList<WimaPolygon*>& WimaPolygonContainer::returnFlatList()
{
    if(_flatListDirty){
        _flatList.clear();

        int count = _itemList.count();
        for(int i = 0; i < count; i++){
            WimaPolygon* poly = _itemList.takeAt(i);
            _flatList.append(poly);
            _flatList.append(poly->subPolygons()); // returns an emptey list, if no sub polygons exist
        }
        _flatListDirty = false;
    }

    return _flatList;
}

int WimaPolygonContainer::count()
{
    return _itemList.size();
}

void WimaPolygonContainer::setFlatListDirty(void)
{
    _flatListDirty = true;
}
