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

KonaImage::KonaImage(KonaClient *Kc, int Id, QStringList Tags, int CreatedAt, int CreatorId, QString Author, int Change, QString Source, int Score, QString Md5, int FileSize, QString FileUrl, bool IsShownInIndex, QString PreviewUrl, int PreviewWidth, int PreviewHeight, int ActualPreviewWidth, int ActualPreviewHeight, QString SampleUrl, int SampleWidth, int SampleHeight, int SampleFileSize, QString JpegUrl, int JpegWidth, int JpegHeight, int JpegFileSize, QString Rating, bool HasChildren, int ParentID, QString Status, int Width, int Height, bool IsHeld, QString FramesPendingString, QString FramesString)
{
    // Reset
    previewStatusCode = 1;
    imageStatusCode = 1;
    jpegStatusCode = 1;
    sampleStatusCode = 1;

    // Copy to RAM
    kc = Kc;
    id = Id;
    tags = Tags;
    createdAt = CreatedAt;
    creatorId = CreatorId;
    author = Author;
    change = Change;
    source = Source;
    score = Score;
    md5 = Md5;
    fileSize = FileSize;
    fileUrl = FileUrl;
    isShownInIndex = IsShownInIndex;
    previewUrl = PreviewUrl;
    previewWidth = PreviewWidth;
    previewHeight = PreviewHeight;
    actualPreviewWidth =  ActualPreviewWidth;
    actualPreviewHeight = ActualPreviewHeight;
    sampleUrl = SampleUrl;
    sampleWidth = SampleWidth;
    sampleHeight = SampleHeight;
    sampleFileSize = SampleFileSize;
    jpegUrl = JpegUrl;
    jpegWidth = JpegWidth;
    jpegHeight = JpegHeight;
    jpegFileSize = JpegFileSize;
    rating = Rating;
    hasChildren = HasChildren;
    parentID = ParentID;
    status = Status;
    width = Width;
    height = Height;
    isHeld = IsHeld;
    framesPendingString = FramesPendingString;
    framesString = FramesString;

    // Initialize preview file
    previewFile = new QFile();
    previewFile->setFileName(KONAIMAGE_PREVIEWPATH);

    // Prepare preview HTTP
    previewHttp = new QHttp("konachan.com"); //TODO: all these konachans.com should be Kc->getServer()
    connect(previewHttp, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),
            this, SLOT(previewResponseHeaderReceived(QHttpResponseHeader)));
    connect(previewHttp, SIGNAL(requestFinished(int,bool)),
            this, SLOT(previewRequestFinished()));


    // Initialize image file (highres)
    imageFile = new QFile();
    imageFile->setFileName(KONAIMAGE_LOCALPATH);

    // Prepare image HTTP
    imageHttp = new QHttp("konachan.com");
    connect(imageHttp, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),
            this, SLOT(imageResponseHeaderReceived(QHttpResponseHeader)));
    connect(imageHttp, SIGNAL(requestFinished(int,bool)),
            this, SLOT(imageRequestFinished()));


    // Initialize jpeg file
    jpegFile = new QFile();
    jpegFile->setFileName(KONAIMAGE_JPEGPATH);

    // Prepare jpeg HTTP
    jpegHttp = new QHttp("konachan.com");
    connect(jpegHttp, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),
            this, SLOT(jpegResponseHeaderReceived(QHttpResponseHeader)));
    connect(jpegHttp, SIGNAL(requestFinished(int,bool)),
            this, SLOT(jpegRequestFinished()));


    // Initialize sample file
    sampleFile = new QFile();
    sampleFile->setFileName(KONAIMAGE_SAMPLEPATH);

    // Prepare sample HTTP
    sampleHttp = new QHttp("konachan.com");
    connect(sampleHttp, SIGNAL(responseHeaderReceived(QHttpResponseHeader)),
            this, SLOT(sampleResponseHeaderReceived(QHttpResponseHeader)));
    connect(sampleHttp, SIGNAL(requestFinished(int,bool)),
            this, SLOT(sampleRequestFinished()));
}

void KonaImage::DownloadPreview(bool overwrite) {
    if (previewStatusCode != 1) return; // Already in progress
    if (!previewFile->exists() || overwrite) {
        previewFile->open(QFile::ReadWrite);
        previewStatusCode = 0;
        previewHttp->get(previewUrl, previewFile);
    }
    else if (previewFile->exists()) {
        previewStatusCode = 200; // Fake HTTP OK
        previewRequestFinished();
    }
}

void KonaImage::previewRequestFinished() {
    //qDebug() << "PREVIEW FINISHED WITH HTTP " << previewStatusCode;
    previewFile->close();
    if (previewStatusCode == 200) previewStatusCode = 1;
    emit previewDownloaded(this, previewFile->fileName());
}

void KonaImage::previewResponseHeaderReceived(QHttpResponseHeader resp) {
    previewStatusCode = resp.statusCode();
}

// "real" image
void KonaImage::DownloadImage(bool overwrite) {
    qDebug() << "Download request of real image: " << this->id;
    if (imageStatusCode != 1) return; // Already in progress

    if (!imageFile->exists() || overwrite) {
        imageFile->open(QFile::ReadWrite);
        imageStatusCode = 0;
        imageHttp->get(fileUrl, imageFile);
    }
    else if (imageFile->exists()) {
        imageFile->open(QFile::ReadWrite);
        QCryptographicHash md5sum(QCryptographicHash::Md5);
        md5sum.addData(imageFile->readAll());
        imageFile->reset();

        if (md5sum.result().toHex() == md5) {
            imageStatusCode = 200; // Fake HTTP OK
            imageRequestFinished();
        }
        else {
            qDebug() << "ERROR: KonaImage: MD5 checksum verification failed!";
            imageStatusCode = 0;
            imageHttp->get(fileUrl, imageFile);
        }
    }
}

void KonaImage::imageRequestFinished() {
    imageFile->close();
    if (imageStatusCode == 200) imageStatusCode = 1;
    emit imageDownloaded(this, imageFile->fileName());
}

void KonaImage::imageResponseHeaderReceived(QHttpResponseHeader resp) {
    imageStatusCode = resp.statusCode();
}

// jpeg image
void KonaImage::DownloadJpeg(bool overwrite) {
    if (jpegStatusCode != 1) return; // Already in progress
    if (!jpegFile->exists() || overwrite) {
        jpegFile->open(QFile::ReadWrite);
        jpegStatusCode = 0;
        jpegHttp->get(jpegUrl, jpegFile);
    }
    else if (jpegFile->exists()) {
        jpegStatusCode = 200; // Fake HTTP OK
        jpegRequestFinished();
    }
}

void KonaImage::jpegRequestFinished() {
    //qDebug() << "Jpeg FINISHED WITH HTTP " << JpegStatusCode;
    jpegFile->close();
    if (jpegStatusCode == 200) jpegStatusCode = 1;
    emit jpegDownloaded(this, jpegFile->fileName());
}

void KonaImage::jpegResponseHeaderReceived(QHttpResponseHeader resp) {
    jpegStatusCode = resp.statusCode();
}


// sample image
void KonaImage::DownloadSample(bool overwrite) {
    if (sampleStatusCode != 1) return; // Already in progress
    if (!sampleFile->exists() || overwrite) {
        sampleFile->open(QFile::ReadWrite);
        sampleStatusCode = 0;
        sampleHttp->get(sampleUrl, sampleFile);
    }
    else if (sampleFile->exists()) {
        sampleStatusCode = 200; // Fake HTTP OK
        sampleRequestFinished();
    }
}

void KonaImage::sampleRequestFinished() {
    //qDebug() << "sample FINISHED WITH HTTP " << sampleStatusCode;
    sampleFile->close();
    if (sampleStatusCode == 200) sampleStatusCode = 1;
    emit sampleDownloaded(this, sampleFile->fileName());
}

void KonaImage::sampleResponseHeaderReceived(QHttpResponseHeader resp) {
    sampleStatusCode = resp.statusCode();
}
