#include "konasearch.h"

#include <QDebug>
#include <QtXml/QDomDocument>

KonaSearch::KonaSearch(KonaClient *Kc, QString Tags, int Page, int Limit)
{   
    // Reset
    searchIsDone = false;

    // Copy search info to RAM
    kc = Kc;

    tags = Tags;
    page = Page;

    if (Limit < 100) {
        limit = Limit;
    }
    else {
        limit = 100;
    }

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

    while (file->exists()) {
        fileID++;
        file->setFileName(kc->getTempDir() + SLASH + "search_" + 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 (limit == 0) {
        searchIsDone = true;
        file->close();
    }
    else {
        searchAgain();
    }
}

KonaSearch::~KonaSearch()
{
    file->close();
    file->remove();
    file->deleteLater();

    http->closeConnection();
    http->close();
    http->deleteLater();
}

void KonaSearch::newSearch(QString Tags, int Page, int Limit) {
    // Reset
    searchIsDone = false;
    result.clear();

    // Update search info to RAM
    tags = Tags;
    page = Page;

    if (Limit < 100) {
        limit = Limit;
    }
    else {
        limit = 100;
    }

    file->close();
    file->remove();
    file->open(QFile::ReadWrite);


    searchAgain();
}

void KonaSearch::searchAgain()
{
    searchIsDone = false;
    file->close();

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

    QUrl url("/post/index.xml?limit=" + QString::number(limit) + "&page=" + QString::number(page) + "&tags=" + tags);
    http->get(url.toString(), file);
}

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

        QDomDocument doc ("search");
        if (!doc.setContent(file)) {
            qDebug() << "KonaSearch: ERROR: Can't parse xml!";
            searchIsDone = true;
            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() != "posts") {
            qDebug() << "KonaSearch: ERROR: Wrong root element!";
            searchIsDone = true;
            emit searchFailed(this, ERROR_SEARCH_FORMAT);
            return;
        }

        QDomElement el = root.firstChildElement("post");
        if (el.isNull()) {
            qDebug() << "KonaSearch: ERROR: Couldn't get first element!";
            searchIsDone = true;
            emit searchFailed(this, ERROR_SEARCH_FORMAT);
            return;
        }


        totalImages = root.attribute("count","-1").toInt();
        offset = root.attribute("offset","-1").toInt();

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

        int x = 0;
        while (!el.isNull()) {
            QStringList Tags = el.attribute("tags", "").split(" ");
            result.append(new KonaImage(kc,
                              el.attribute("id", "-1").toInt(),
                              Tags,
                              el.attribute("created_at", "-1").toInt(),
                              el.attribute("creator_id", "-1").toInt(),
                              el.attribute("author", ""),
                              el.attribute("change","-1").toInt(),
                              el.attribute("source", ""),
                              el.attribute("score", "-1").toInt(),
                              el.attribute("md5"),
                              el.attribute("file_size", "-1").toInt(),
                              el.attribute("file_url", ""),
                              toBool(el.attribute("is_shown_in_index", "")),
                              el.attribute("preview_url", ""),
                              el.attribute("preview_width", "-1").toInt(),
                              el.attribute("preview_height", "-1").toInt(),
                              el.attribute("actual_preview_width", "-1").toInt(),
                              el.attribute("actual_preview_height", "-1").toInt(),
                              el.attribute("sample_url", ""),
                              el.attribute("sample_width", "-1").toInt(),
                              el.attribute("sample_height", "-1").toInt(),
                              el.attribute("sample_file_size", "-1").toInt(),
                              el.attribute("jpeg_url", ""),
                              el.attribute("jpeg_width", "-1").toInt(),
                              el.attribute("jpeg_height", "-1").toInt(),
                              el.attribute("jpeg_file_size", "-1").toInt(),
                              el.attribute("rating", ""),
                              el.attribute("has_children", "").toInt(),
                              el.attribute("parent_id", "-1").toInt(),
                              el.attribute("status", ""),
                              el.attribute("width", "-1").toInt(),
                              el.attribute("height", "-1").toInt(),
                              toBool(el.attribute("is_held")),
                              el.attribute("frames_pending_string", ""),
                              el.attribute("frames_string")
                              ));
            x++;
            el = root.elementsByTagName("post").at(x).toElement();
        }

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

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