// 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 carry out downloading of a remote file
// This implementation is based on a tutorial at "http://www.bogotobogo.com/Qt/Qt5_Downloading_Files_QNetworkAccessManager_QNetworkRequest.php"
#include "filedownloader.h"
#include <QApplication>
#include <QMessageBox>

FileDownloader::FileDownloader(QObject *parent) : QObject(parent)
{
    // Initializing the network access manager
    netManager = new QNetworkAccessManager(this);

    // Setting the variable indicating that by default the path is specified as a string
    this->downloadIsQtUrl = false;

    // Initializing connections (used to listen to a responce from the server etc.)
    createActions();
}

// Method to create actions
void FileDownloader::createActions()
{
    connect(this->netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}

// Method to carry out download of a file
void FileDownloader::download()
{
    if (this->downloadIsQtUrl == true)
    {
        netManager->get(QNetworkRequest(this->downloadUrl));
    }
    else
    {
        netManager->get(QNetworkRequest(QUrl(this->downloadPath)));
    }
}

void FileDownloader::replyFinished (QNetworkReply *reply)
{
    QByteArray replyData;  // Data downloaded from a remote server
    bool success;   // Variable indicating if the data request has been a success
    int numReply;   // Reply in a numerical form


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

    // Determining from the numerical reply if the request was successful
    if (numReply == 200)
    {
        // Indicating that data retrieved successfully
        success = true;

        // Getting the reply (containing the HITRAN database data)
        replyData = reply->readAll();

        // Saving the data to a file if the corresponding variable is set indicating that the data is supposed to be saved
        if (this->saveToHarddrive)
        {
            QFile outFile(this->savePath);
            // Opening the text file for writing
            if (outFile.open(QIODevice::WriteOnly))
            {
                QTextStream out(&outFile);
                out << replyData;
                outFile.flush();
                outFile.close();
            }
        }
    }
    else
    {
        // Indicating that the data could not be retrieved
        success = false;
    }

    // Emitting a signal with the downloaded data
    emit dataDownloaded(&replyData, success);
}

// Method to get and set the save path
QString FileDownloader::getSavePath() { return this->savePath; }
void FileDownloader::setSavePath(QString newSavePath) { this->savePath = newSavePath; }

// Getting and setting the download path
QString FileDownloader::getDownloadPath() { return this->downloadPath; }
void FileDownloader::setDownloadPath(QString newDownloadPath) { this->downloadPath = newDownloadPath; }

// Methods to get and set a variable indicating if the data is to be saved to local storage
bool FileDownloader::getSaveToHarddive() { return this->saveToHarddrive; }
void FileDownloader::setSaveToHarddrive(bool newSaveToHarddrive) { this->saveToHarddrive = newSaveToHarddrive; }

// Getting and setting the download URL
QUrl FileDownloader::getDownloadUrl() { return this->downloadUrl; }
void FileDownloader::setDownloadUrl(QUrl newDownloadUrl) { this->downloadUrl = newDownloadUrl; }

// Method sets a variable indicating if a URL or String is passed to the downloader with the download address
bool FileDownloader::getDownloadIsQtUrl() { return this->downloadIsQtUrl; }
void FileDownloader::setDownloadIsQtUrl(bool isUrl) { this->downloadIsQtUrl = isUrl; }
