/*
 * 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/>.
 */

// Own

#include "utils.h"

// Qt

#include <QJsonDocument>
#include <QXmlStreamReader>
#include <QUrlQuery>

// KDE

#include "libdanbooru_debug.h"

namespace Danbooru
{

QUrl requestUrl(QUrl &url, const QString &path,
                const QString &username, const QString &password,
                const dictMap &parameters, const QStringList &tags)
{

    QUrl danbooruUrl = QUrl(url);
    danbooruUrl = danbooruUrl.adjusted(QUrl::StripTrailingSlash);
    danbooruUrl.setPath(danbooruUrl.path() + '/' + path);

    // If we have parameters, add them

    QUrlQuery query;

    if (!parameters.isEmpty()) {

        for (auto it = parameters.cbegin(), e = parameters.cend(); it != e; ++it) {
            query.addQueryItem(it.key(), it.value());
        }

    }

    // Now, let's add tags should we have them

    if (!tags.isEmpty()) {
        query.addQueryItem("tags", tags.join(" "));
    }

    danbooruUrl.setQuery(query);

    if (!username.isEmpty() && !password.isEmpty()) {
        danbooruUrl.setUserName(username);
        danbooruUrl.setPassword(password);
    }

    return danbooruUrl;
}

QUrl requestUrl(QUrl &url, const QString &path, const QString &username,
                const QString &password, const dictMap &parameters)
{

    QUrl danbooruUrl = QUrl(url);
    danbooruUrl = danbooruUrl.adjusted(QUrl::StripTrailingSlash);
    danbooruUrl.setPath(danbooruUrl.path() + '/' + path);

    // If we have parameters, add them

    QUrlQuery query;

    if (!parameters.isEmpty()) {

        for (auto it = parameters.cbegin(), e = parameters.cend(); it != e; ++it) {
            query.addQueryItem(it.key(), it.value());
        }

    }

    danbooruUrl.setQuery(query);

    if (!username.isEmpty() && !password.isEmpty()) {
        danbooruUrl.setUserName(username);
        danbooruUrl.setPassword(password);
    }

    return danbooruUrl;
}

QUrl requestUrl(QUrl &url, const QString &path, const QString &username,
                const QString &password)
{
    QUrl danbooruUrl = QUrl(url);
    danbooruUrl = danbooruUrl.adjusted(QUrl::StripTrailingSlash);
    danbooruUrl.setPath(danbooruUrl.path() + '/' + path);

    if (!username.isEmpty() && !password.isEmpty()) {
        danbooruUrl.setUserName(username);
        danbooruUrl.setPassword(password);
    }

    return danbooruUrl;
}

QList< QVariant > parseDanbooruResult(QByteArray data, QString xlmElement, bool *result)
{

    QXmlStreamReader reader;
    reader.addData(data);

    QList<QVariant> postData;

    while (!reader.atEnd() && !reader.hasError()) {

        QXmlStreamReader::TokenType token = reader.readNext();

        if (token == QXmlStreamReader::StartDocument) {
            continue;
        }

        if (token == QXmlStreamReader::StartElement &&
                reader.name() == xlmElement)  {

            QVariantMap values;

            QXmlStreamAttributes attributes = reader.attributes();

//                 qCDebug(LIBDANBOORU) << attributes;

            for (auto attribute : attributes) {
                values.insert(attribute.name().toString(),
                              attribute.value().toString());
            }

            if (values.isEmpty()) {
                *result = false;
                qCWarning(LIBDANBOORU) << "No results found when parsing XML";
                return QList<QVariant>();
            }

            QVariant converted = QVariant(values);

            postData.append(converted);
        }
    }
    *result = true;
    return postData;
}

QVariant parseDanbooruResult(QByteArray data, bool *result)
{

    QJsonDocument parsed = QJsonDocument::fromJson(data);

    if (parsed.isNull()) {
        return QList<QVariant>();
    }

    QVariant postData = parsed.toVariant();

    *result = true;

    return postData;
}

bool isPostBlacklisted(DanbooruPost *post, QSet<QString> blacklist, DanbooruPost::Ratings maxRating)
{

    if (post->rating() > maxRating) {
        return true;
    }

    for (auto tag : post->tags()) {

        if (blacklist.contains(tag)) {
            return true;
        }
    }

    return false;

}

} // namespace Danbooru
