/*
 * Copyright 2014 Mihai Niculescu <q.quark@gmail.com>
 *
 * This file is part of EqualX Project (https://launchpad.net/equalx/)
 *
 * EqualX 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.
 *
 * EqualX 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "Library/Library.h"
#include "HistoryPanel/HistoryListModel.h"

HistoryListModel::HistoryListModel(LibraryManager *library, QObject *parent) :
    QAbstractListModel(parent),
    mLibrary(library),
    mChildren(0)
{
    mHistorySize = mLibrary->historySize();

    connect(mLibrary, SIGNAL(historyChanged()), this, SLOT(onHistoryChanged()) );
}

HistoryListModel::~HistoryListModel()
{
}

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

    if (index.row() >= mHistorySize || index.row() < 0)
        return QVariant();

    if (role == Qt::DisplayRole){
        return mLibrary->getHistoryRow(mHistorySize-index.row()).basicData();
    }

    return QVariant();
}

bool HistoryListModel::canFetchMore(const QModelIndex &/*parent*/) const
{
    if(mChildren < mHistorySize){
        return true;
    }
    else {
        return false;
    }
}

void HistoryListModel::fetchMore(const QModelIndex &/*parent*/)
{
    int remainder = mHistorySize - mChildren;
    int itemsToFetch = qMin(10, remainder);

    beginInsertRows(QModelIndex(), mChildren, mChildren+itemsToFetch-1);

    mChildren += itemsToFetch;

    endInsertRows();

}

int HistoryListModel::rowCount(const QModelIndex &/*parent*/) const
{
    return mChildren;
}

Qt::DropActions HistoryListModel::supportedDropActions() const
{
    return Qt::IgnoreAction;
}

Qt::DropActions HistoryListModel::supportedDragActions() const
{
    return Qt::IgnoreAction;
}

Qt::ItemFlags HistoryListModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;

    Qt::ItemFlags itemFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    return itemFlags;
}

void HistoryListModel::onHistoryChanged()
{
    beginResetModel();
    mHistorySize = mLibrary->historySize();

    if(mHistorySize==0)
        mChildren = 0;

    endResetModel();
}
