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

KonaRelatedTags::KonaRelatedTags(KonaClient *Kc, QString Tags, QString Type)
{
    kc = Kc;
    tags = Tags;
    type = Type;


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

    while (file->exists()) {
        fileID++;
        file->setFileName(kc->getTempDir() + SLASH + "relTags_" + 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()));

    // Search
    if (Tags == "") {
        searchIsDone = true;
    }
    else {
        searchAgain();
    }
}

void KonaRelatedTags::newSearch(QString Tags, QString Type)
{
    if (Tags != "__KEEPOLD__") tags = Tags;
    if (Type != "__KEEPOLD__") type = Type;

    searchAgain();
}

void KonaRelatedTags::searchAgain() {
    result.clear();
    searchIsDone = false;

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

    QUrl url("/tag/related.xml?tags=" + tags + (type != "" ? "&type=" + type : ""));
    qDebug() << url.toString();
    http->get(url.toString(), file);
}

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

        QDomDocument doc ("search");
        if (!doc.setContent(file)) {
            qDebug() << "KonaRelatedTags: 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() << "KonaRelatedTags: ERROR: Wrong root element!";
            emit searchFailed(this, ERROR_TAGS_FORMAT);
            return;
        }

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


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

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

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

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