// bytran -|- spectral calculations for portable devices using the HITRAN database
//
// Developed by Dzianis Pliutau (Denis Plutov) and Kostya Roslyakov
// www.bytran.org | contact@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 used to login to a server (HITRAN server uses the POST method to authenticate)
#include "serverlogin.h"
#include <QUrlQuery>
#include <QNetworkReply>
#include <QNetworkCookie>
#include <QNetworkCookieJar>
#include <QMessageBox>
#include <QFile>

ServerLogin::ServerLogin(QObject *parent) : QObject(parent)
{
    // Initializing the cookiejar
    //jar = new CookieJar(this);

    // Initializing the newtwork access manager
    netManager = new QNetworkAccessManager(this);

    // Method to create actions
    createActions();
}

// Getting and setting the host name
QString ServerLogin::getHostName() { return this->hostName; }
void ServerLogin::setHostName(QString newHostName) { this->hostName = newHostName; }

// Methods to get and set the email and password
QString ServerLogin::getEmail() { return this->email; }
void ServerLogin::setEmail(QString newEmail) { this->email = newEmail; }
QString ServerLogin::getPassword() { return this->password; }
void ServerLogin::setPassword(QString newPassword) { this->password = newPassword; }

// Method to contain connections
void ServerLogin::createActions()
{
    // Connection of the newtwork manager object with the HTTP reply slot
    connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinish(QNetworkReply*)));
    connect(netManager, SIGNAL(finished(QNetworkReply*)), netManager, SLOT(deleteLater()));
}

void ServerLogin::onFinish(QNetworkReply *reply){

    QString networkReply;


    // This module has never been implemented due to the incompatibility with the HITRAN online server configuration

    // Returns the HttpCode
    // qDebug()<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
    // Returns the saved cookies fo the connection
    // qDebug()<<netManager->cookieJar()->cookiesForUrl(QUrl(this->hostName));

    // This signal should only be emitted if the reply from the server indicates that the authentication was successful
    emit authenticationSuccessful();
}

// Method to authenticate with a remote server
void ServerLogin::authenticate()
{
    // Initializing an object to handle the cookie jar
    // netManager->setCookieJar(jar);

    // Setting up cookies
    netManager->setCookieJar(new QNetworkCookieJar(netManager));

    // According to stack overflow this cookie jar needs to be sub-classed and the saving of file (cookie) should be implemented
    //     QFile f("/tmp/cookie.txt");
    //     f.open(QIODevice::ReadOnly);
    //     QDataStream s(&f);
    //     while(!s.atEnd()){
    //         QByteArray c;
    //         s >> c;
    //         QList<QNetworkCookie> list = QNetworkCookie::parseCookies(c);
    //         jar->insertCookie(list.at(0));
    //     }

    QNetworkRequest req;
    req.setUrl(QUrl(this->hostName));
    //req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    req.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");

    QByteArray postData;
    postData.append("email=" + this->email + "&");
    postData.append("password=" + this->password);
    netManager->post(req, postData);

    // Posting the login information to a remote server
    // QUrlQuery postData;
    // postData.addQueryItem("email", this->email);
    // postData.addQueryItem("password", this->password);
    // QUrl Url(this->hostName);
    // Url.setQuery(postData);
    // QNetworkRequest netRequest(Url);
    // netRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    // // netManager->get(netRequest);
    // netManager->post(netRequest, postData.toString(QUrl::FullyEncoded).toUtf8());

    // May replace this with the file download example instead if this HTTP post does not work, then downloading the file might or else hiddeh webbrowser, maybe this will work
}
