// bytran -|- spectral calculations for portable devices using the HITRAN database
//
// Developed by Dzianis Pliutau (Denis Plutov) and Kostya Roslyakov
// www.bytran.org | bytran@bytran.org
// Copyright (c) 2016 Dzianis Pliutau
// Distributed under the MIT license
//
// The MIT License (MIT)
// Copyright (c) 2016 Dzianis Pliutau
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.



// Object to request data from the HITRAN-online server
#include "hitranrequestdata.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QMessageBox>
#include <QApplication>

HitranRequestData::HitranRequestData(QObject *parent) : QObject(parent)
{
    // Initializing the network manager
    networkManager = new QNetworkAccessManager();

    // Initializing the file downloader
    downloader = new FileDownloader();
    downloader->setSaveToHarddrive(false);

    // Method to create actions
    createActions();

    // By default a case with no authentication is used
    this->authenCase = false;
}

// Method to create connections
void HitranRequestData::createActions()
{
    connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
    connect(this->downloader, SIGNAL(dataDownloaded(QByteArray*, bool)), this, SIGNAL(hitranDataReturned(QByteArray*, bool)));
}

// Slot is executed when with the download progress updates
void HitranRequestData::onDownloadProgressUpdate(qint64 bytesReceived, qint64 bytesToAquire)
{
    //    QString auxStr;

    //    auxStr = "Downloaded bytes " + QString::number(bytesReceived) + " of " + QString::number(bytesToAquire);
    //    emit notify(auxStr, 0, true, false);
    QApplication::processEvents();
}

// Slot is executed when there an error receiving reply from a network request
void HitranRequestData::onReplyError(QNetworkReply::NetworkError error)
{
}

// Method to send a request to a remote server
void HitranRequestData::requestDataFromRemoteHost()
{
    QNetworkRequest netRequest;
    netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    netRequest.setUrl(QUrl(this->requestStr));    
    reply = networkManager->get(netRequest);
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(onDownloadProgressUpdate(qint64,qint64)));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onReplyError(QNetworkReply::NetworkError)));
}

// Methods to get and set the requests to be sent to the remote server
QString HitranRequestData::getRequestStr() { return this->requestStr; }
void HitranRequestData::setRequestStr(QString newRequestStr) { this->requestStr = newRequestStr; }

// Slot executed when a reply is received from the network
void HitranRequestData::onFinished(QNetworkReply *networkReply)
{
    QString downloadFilePath;
    QByteArray replyData;
    int numReply;  // Numerical reply

    // Getting the complete network reply responce
    replyData = networkReply->readAll();

    // Gettting a status reply from the server responce to determine if the data retrieval was successful
    numReply = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (numReply == 200)
    {
        // Determining if this is an authentication case or not (determied from the way the returned page looks like)

        // If this is an authentication case, returning the path to the file to download (or the file name at least),
        // otherwise returning the complete downloaded dataset as it is retured if no authentication is necessary
        if (authenCase == true)
        {
           // Downloading the HITRAN file
           downloader->setDownloadPath(downloadFilePath);
           downloader->download();
        }
        else
        {
           // Emitting a signal with the generated HITRAN data
           emit hitranDataReturned(&replyData, true);
        }
    }
    else
    {
        // Emitting a signal with the generated HITRAN data and indicating that the data retirieval was unsuccessrul
        emit hitranDataReturned(&replyData, false);
    }

    // No response right now (maybe the authentification does not work or the cookies need to be set.).

}
