/*
 * Copyright 2015 Luca Beltrame <lbeltrame@kde.org>
 *
 * This file is part of Danbooru Client.
 *
 * Danbooru Client is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Danbooru Client is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Danbooru Client. If not, see <http://www.gnu.org/licenses/>.
 */

#include "danboorupoolmodel.h"
#include "libdanbooru/danboorupool.h"

#include <QDebug>

#include <KLocalizedString>

namespace Danbooru {

DanbooruPoolModel::DanbooruPoolModel(QObject* parent): QAbstractTableModel(parent)
{
}

const QStringList DanbooruPoolModel::m_headerNames = { i18n("ID"),
    i18n("Name"), i18n("Posts"), i18n("Description") };

DanbooruPoolModel::~DanbooruPoolModel()
{
    if (!m_items.isEmpty()) {
        qDeleteAll(m_items);
        m_items.clear();
    }
}

void DanbooruPoolModel::addPool(DanbooruPool *pool)
{
    beginInsertRows(QModelIndex(), m_items.size(), m_items.size());
    m_items.append(pool);
    endInsertRows();
}

int DanbooruPoolModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return m_items.size();
}

int DanbooruPoolModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return 4;
}

QVariant DanbooruPoolModel::data(const QModelIndex& index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (index.row() >= m_items.size() || index.row() < 0) {
        return QVariant();
    }

    if (m_items.isEmpty()) {
        return QVariant();
    }

    DanbooruPool* pool = m_items.at(index.row());

    if (role == Qt::DisplayRole) {

        if (index.column() == 0) {
            return pool->id();
        } else if (index.column() == 1) {
            return pool->name();
        } else if (index.column() == 2) {
            return pool->postCount();
        } else if (index.column() == 3) {
            return pool->description();
        }
    }

    return QVariant();

}

QVariant DanbooruPoolModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
        return m_headerNames.at(section);
    }

    return QAbstractTableModel::headerData(section, orientation, role);

}

void DanbooruPoolModel::clear()
{
     if (m_items.isEmpty()) {
        return;
    }

    beginResetModel();
    qDeleteAll(m_items);
    m_items.clear();
    endResetModel();
}

DanbooruPool* DanbooruPoolModel::poolAt(int index) const
{
    return m_items.at(index);
}



} // namespace Danbooru