/***************************** 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 "MvQNetworkProxyFactory.h"

#include "MvApplication.h"
#include "MvRequest.h"

MvQNetworkProxyFactory::MvQNetworkProxyFactory()
{
    useProxy_ = false;
    proxy_.setType(QNetworkProxy::HttpProxy);
    updateSettings();
}

void MvQNetworkProxyFactory::updateSettings()
{
    useProxy_ = false;
    noProxyLst_.clear();

    MvRequest myPref = MvApplication::getExpandedPreferences();
    // myPref=ObjectList::ExpandRequest(myPref,EXPAND_DEFAULTS);

    const char* useProxy = myPref("USE_NETWORK_PROXY");
    if ((useProxy != nullptr))
        useProxy_ = (strcmp(useProxy, "Yes") == 0 ||
                     strcmp(useProxy, "YES") == 0 ||
                     strcmp(useProxy, "yes") == 0)
                        ? true
                        : false;

    if (useProxy_) {
        const char* proxyUrl = myPref("PROXY_URL");
        if (proxyUrl)
            proxy_.setHostName(QString(proxyUrl));

        const char* proxyPort = myPref("PROXY_PORT");
        if (proxyPort)
            proxy_.setPort(QString::fromLatin1(proxyPort).toInt());

        const char* noProxy = myPref("NO_PROXY_FOR");

        if (noProxy) {
            QStringList lst = QString::fromLatin1(noProxy).split(",");
            foreach (QString s, lst) {
                noProxyLst_ << s.simplified();
            }
        }
    }
}


QList<QNetworkProxy> MvQNetworkProxyFactory::queryProxy(const QNetworkProxyQuery& query)
{
    QList<QNetworkProxy> res;

    updateSettings();

    if (!useProxy_)
        return res;

    foreach (QString p, noProxyLst_) {
        if (query.peerHostName().endsWith(p)) {
            return res;
        }
    }

    res << proxy_;

    return res;
}
