/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QDebug>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QNetworkReply>

#include "MvQNetworkAccessManager.h"
#include "MvQNetworkProxyFactory.h"

MvQNetworkAccessManager::MvQNetworkAccessManager(QObject* parent) :
    QNetworkAccessManager(parent)
{
    // network_ = new QNetworkAccessManager(this);

    connect(this, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slotReplyFinished(QNetworkReply*)));

    auto* proxyFactory = new MvQNetworkProxyFactory;
    setProxyFactory(proxyFactory);

    // Set proxy
    /*	QNetworkProxy proxy;
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName("proxy.ecmwf.int");
        proxy.setPort(3333);

        setProxy(proxy);*/
}

void MvQNetworkAccessManager::slotReplyFinished(QNetworkReply* reply)
{
    // Reply is finished!
    // We'll ask for the reply about the Redirection attribute
    QVariant possibleRedirectUrl =
        reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    QVariant v = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
    // qDebug() << "Reason: " << v.toInt();

    v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    // qDebug() << "Status: " << v.toByteArray();

    // We'll deduct if the redirection is valid in the redirectUrl function
    urlRedirectedTo_ = redirectUrl(possibleRedirectUrl.toUrl(),
                                   urlRedirectedTo_);

    // If the URL is not empty, we're being redirected.
    if (!urlRedirectedTo_.isEmpty()) {
        // qDebug() << "Redirection to: " << urlRedirectedTo_;
        get(QNetworkRequest(urlRedirectedTo_));
        reply->deleteLater();
    }
    else {
        emit replyReadyToProcess(reply);
        urlRedirectedTo_.clear();
    }
}

QUrl MvQNetworkAccessManager::redirectUrl(const QUrl& possibleRedirectUrl,
                                          const QUrl& oldRedirectUrl) const
{
    QUrl redirectUrl;

    // Check if the URL is empty and
    // that we aren't being fooled into a infinite redirect loop.
    if (!possibleRedirectUrl.isEmpty() &&
        possibleRedirectUrl != oldRedirectUrl) {
        redirectUrl = possibleRedirectUrl;
    }
    return redirectUrl;
}
