/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 2012  Benjamin Mesing <email>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "networksettings.h"

#include <QProcess>
#include <QUrl>

#include "helpers.h"
#include "xmldata.h"

namespace NUtil 
{

NetworkSettings::NetworkSettings(ProxyType type, string host, int port)
{
	_host = host;
	_port = port;
	setProxyType(type);
}

NetworkSettings::~NetworkSettings()
{
}

bool NetworkSettings::loadSystemProxy() 
{
	QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
	if (env.contains("http_proxy")) 
	{
		QUrl proxyUrl(env.value("http_proxy"));
		_host = proxyUrl.host().toStdString();
		_port = proxyUrl.port();
		return true;
	}
	else
		return false;
}

void NetworkSettings::setProxyType(ProxyType type) 
{
	_proxyType = type;
	switch (type) {
		case NO_PROXY:
			_useProxy = false;
			break;
		case SYSTEM_PROXY:
			_useProxy = loadSystemProxy();	
			break;
		case CUSTOM_PROXY:
			_useProxy = true;
			break;
	}
	updateQProxy();
}

void NetworkSettings::updateQProxy()
{
    if (_useProxy) {
        QNetworkProxy proxy;
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(toQString(_host));
        proxy.setPort(_port);
        QNetworkProxy::setApplicationProxy(proxy);
    } else {
        QNetworkProxy proxy;
        proxy.setType(QNetworkProxy::NoProxy);
        QNetworkProxy::setApplicationProxy(proxy);
    }
}

QDomElement NetworkSettings::loadSettings ( QDomElement source )
{
	if (source.tagName() != "network")
		return source;
	int type;
	NXml::getAttribute(source, type, "proxyType", (int) SYSTEM_PROXY);
	NXml::getAttribute(source, _host, "httpProxyHost", "");
	NXml::getAttribute(source, _port, "httpProxyPort", 0);
	setProxyType((ProxyType) type);
	return NXml::getNextElement(source);

}

void NetworkSettings::saveSettings ( NXml::XmlData& outData, QDomElement parent ) const
{
	QDomElement element = outData.addElement(parent, "network");
	outData.addAttribute(element, _proxyType, "proxyType");
	if (_host != "") {
		outData.addAttribute(element, _host, "httpProxyHost");
		outData.addAttribute(element, _port, "httpProxyPort");
	}
}

} // namespace NUtil

