/**************************************************************************
** Piperka Client
** Copyright (C) 2019  Kari Pahula
**
** This program 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 2 of the License, or
** (at your option) any later version.
**
** This program 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, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**************************************************************************/
#include "recommend.h"

RecommendModel::RecommendModel(QObject *parent)
    : QSortFilterProxyModel(parent)
{
    sort(0);
}

void RecommendModel::load()
{
    emit loadRecommend();
}

void RecommendModel::setSource(QAbstractItemModel *model)
{
    setSourceModel(model);
}

void RecommendModel::loadRecommendComplete(const QJsonDocument &doc)
{
    QJsonArray recommends = doc.array();
    bool wasEmpty = recommendRanks.empty();
    recommendRanks.clear();
    int i = 1;
    for (QJsonArray::const_iterator iter = recommends.constBegin(); iter != recommends.constEnd(); ++iter, ++i)
        recommendRanks[(*iter).toInt()] = i;

    if (recommendRanks.empty() != wasEmpty)
        emit noRecommendationsChanged();

    invalidate();
    invalidateFilter();
}

bool RecommendModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    QModelIndex index = sourceModel()->index(source_row, 0, source_parent);
    int cid = sourceModel()->data(index, ComicModel::CidRole).toInt();
    return recommendRanks.contains(cid);
}

bool RecommendModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
    int cid1 = sourceModel()->data(source_left, ComicModel::CidRole).toInt();
    int cid2 = sourceModel()->data(source_right, ComicModel::CidRole).toInt();
    return recommendRanks[cid1] < recommendRanks[cid2];
}
