/*
    <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() : _port(-1)
{
	_pNetwork = new QNetworkAccessManager();
	setProxyType(NO_PROXY);
	
}

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

NetworkSettings::~NetworkSettings()
{
	delete _pNetwork;
}

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()
{
	//_qNetworkProxy;
	_pNetwork->setProxy(*(new QNetworkProxy(_useProxy ? QNetworkProxy::HttpProxy : QNetworkProxy::NoProxy,
								toQString(_host), _port)));
}

QNetworkAccessManager* NetworkSettings::network() 
{
	return _pNetwork;
}

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

