#include "konatags.h"
#include <QDebug>

KonaTags::KonaTags(KonaClient *Kc, QString Name, int Limit, int Page, QString Order, int Id, int AfterId, QString NamePattern)
{
    kc = Kc;
    name = Name;
    limit = Limit;
    page = Page;
    order = Order;
    id = Id;
    afterId = AfterId;
    namePattern = NamePattern;


    // Initialize temp file
    int fileID = 0;
    file = new QFile(kc->getTempDir() + SLASH + "tags_0");

    while (file->exists()) {
        fileID++;
        file->setFileName(kc->getTempDir() + SLASH + "tags_" + QString::number(fileID));
    }


    // Prepare HTTP
    http = new QHttp(kc->getServer());
    connect(http, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),
            this, SLOT(responseHeaderReceived(QHttpResponseHeader)));
    connect(http, SIGNAL(requestFinished(int,bool)),
            this, SLOT(requestFinished()));


    if (limit != -1) searchAgain();
    else searchIsDone = true;
}

void KonaTags::searchAgain() {
    searchIsDone = false;

    statusCode = 0;
    if (!file->open(QIODevice::ReadWrite)) {
        qDebug() << "KonaTags: ERROR: Can't open temp file for search!";
        emit searchFailed(this, ERROR_TAGS_TEMPFILE);
        return;
    }

    QString optParams;
    optParams += (id != -1 ? "&id=" + QString::number(id) : "");
    optParams += (afterId != -1 ? "&after_id=" + QString::number(afterId) : "");
    QUrl url("/tag/index.xml?name=" + name + "&page=" + QString::number(page) + "&limit=" + QString::number(limit) + "&order=" + order + "&name_pattern=" + namePattern + optParams);
    http->get(url.toString(), file);
}

void KonaTags::requestFinished() {
    if (statusCode == 200) {
        file->flush();
        file->reset();

        QDomDocument doc ("search");
        if (!doc.setContent(file)) {
            qDebug() << "KonaSearch: ERROR: Can't parse xml!";
            emit searchFailed(this, ERROR_SEARCH_XML);
            file->close();
            file->remove();
            return;
        }
        file->close();
        file->remove(); // We don't need it anymore

        QDomElement root = doc.documentElement();
        if (root.tagName() != "tags") {
            qDebug() << "KonaTags: ERROR: Wrong root element!";
            emit searchFailed(this, ERROR_TAGS_FORMAT);
            return;
        }

        QDomElement el = root.firstChildElement("tag");
        if (el.isNull()) {
            qDebug() << "KonaTags: ERROR: Couldn't get first element!";
            emit searchFailed(this, ERROR_TAGS_FORMAT);
            return;
        }


#define toBool(a) (a == "true" ? true : false)

        int x = 0;
        while (!el.isNull()) {
            result.append(new KonaTag(el.attribute("id", "0").toInt(),
                                      el.attribute("name"),
                                      el.attribute("count").toInt(),
                                      el.attribute("type").toInt(),
                                      toBool(el.attribute("ambiguous"))));
            x++;
            el = root.elementsByTagName("tag").at(x).toElement();
        }

        qDebug() << "KonaTags: Search finished!";
        searchIsDone = true;
        emit searchFinished(this);
    }
    else {
        qDebug() << "KonaTags: ERROR: " << "Received HTTP error code: " << statusCode;
        emit searchFailed(this, ERROR_SEARCH_HTTP);
    }
}

void KonaTags::responseHeaderReceived(QHttpResponseHeader resp) {
    statusCode = resp.statusCode();
}

void KonaTags::newSearch(QString Name, int Limit, int Page, QString Order, int Id, int AfterId, QString NamePattern) {
    // Reset
    searchIsDone = false;
    result.clear();

    // Update search info to RAM
    if (Name != "__KEEPOLD__") name = Name;
    if (Limit != -1) limit = Limit;
    if (Page != -1) page = Page;
    if (Order != "__KEEPOLD__") order = Order;
    if (Id != -1) id = Id;
    if (AfterId != -1) afterId = AfterId;
    if (NamePattern != "__KEEPOLD__") namePattern = NamePattern;

    file->close();
    file->remove();

    searchAgain();
}
