#include "treeitem.h"

#include <QDebug>

TreeItem::TreeItem(const QVector<QVariant> &data, TreeItem *parent)
    : mItemData(data),
      mParentItem(parent)
{
    //qDebug() << data;
    if (mParentItem)
    {
        mParentItem->mChildItems << this;
    }
}

TreeItem::~TreeItem()
{
    qDeleteAll(mChildItems);
}

TreeItem *TreeItem::child(int number)
{
    if (number < 0 || number >= mChildItems.size())
        return nullptr;
    return mChildItems.at(number);
}

int TreeItem::childCount() const
{
    return mChildItems.count();
}

int TreeItem::childNumber() const
{
    if (mParentItem)
        return mParentItem->mChildItems.indexOf(const_cast<TreeItem*>(this));
    return 0;
}

int TreeItem::columnCount() const
{
    return mItemData.count();
}

QVariant TreeItem::data(int column) const
{
    if (column < 0 || column >= mItemData.size())
        return QVariant();
    return mItemData.at(column);
}


bool TreeItem::insertChildren(int position, int count, int columns)
{
    if (position < 0 || position > mChildItems.size())
        return false;

    for (int row = 0; row < count; ++row) 
    {
        QVector<QVariant> data(columns);
        TreeItem *item = new TreeItem(data, this);
        mChildItems.insert(position, item);
    }

    return true;
}

bool TreeItem::insertColumns(int position, int columns)
{
    if (position < 0 || position > mItemData.size())
        return false;

    for (int column = 0; column < columns; ++column)
        mItemData.insert(position, QVariant());

    for (TreeItem *child : qAsConst(mChildItems))
        child->insertColumns(position, columns);

    return true;
}

TreeItem *TreeItem::parent()
{
    return mParentItem;
}

bool TreeItem::removeChildren(int position, int count)
{
    if (position < 0 || position + count > mChildItems.size())
        return false;

    for (int row = 0; row < count; ++row)
        delete mChildItems.takeAt(position);

    return true;
}


bool TreeItem::removeColumns(int position, int columns)
{
    if (position < 0 || position + columns > mItemData.size())
        return false;

    for (int column = 0; column < columns; ++column)
        mItemData.remove(position);

    for (TreeItem *child : qAsConst(mChildItems))
        child->removeColumns(position, columns);

    return true;
}


bool TreeItem::setData(int column, const QVariant &value)
{
    if (column < 0 || column >= mItemData.size())
        return false;

    mItemData[column] = value;
    return true;
}

void TreeItem::clear()
{
    removeChildren(0, childCount());
}

void TreeItem::addChildren(TreeItem* item)
{
    if(!mChildItems.contains(item))
    {
        mChildItems.append(item);
    }
}

void TreeItem::setFieldPath(const QString &path)
{
    mFieldPath = path;
}

QString TreeItem::fieldPath()
{
    return mFieldPath;
}

