/***************************************************************************
 *
 * knetworkmanager-connection.cpp - A NetworkManager frontend for KDE
 *
 * Copyright (C) 2005, 2006 Novell, Inc.
 *
 * Author: Helmut Schaa <hschaa@suse.de>, <helmut.schaa@gmx.de>
 *
 * 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 2 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 **************************************************************************/

/* qt headers */
#include <tqvaluelist.h>

/* kde headers */
#include <kdebug.h>
#include <tdelocale.h>

/* TQDbus headers */
#include <tqdbusconnection.h>
#include <tqdbusobjectpath.h>
#include <tqdbusdata.h>
#include <tqdbusdatamap.h>
#include <tqdbusvariant.h>

/* NM headers */
#include <NetworkManager.h>

/* knetworkmanager headers */
#include "knetworkmanager.h"
#include "knetworkmanager-connection.h"
#include "knetworkmanager-connection_dbus.h"
#include "knetworkmanager-connection_secrets_dbus.h"
#include "knetworkmanager-connection_setting.h"
#include "knetworkmanager-nmsettings.h"
#include <stdio.h>

extern unsigned char vpn_new_credentials_needed;

using namespace ConnectionSettings;

namespace ConnectionSettings
{

class ConnectionPrivate
{
	public:
		ConnectionPrivate(Connection* parent)
    {
			conn_dbus = new ConnectionDBus(parent);
			conn_secrets_dbus = new ConnectionSecretsDBus(parent);
			secrets_requested = false;
		}
		~ConnectionPrivate() {}

		TQT_DBusObjectPath        obj_path;
		ConnectionDBus*        conn_dbus;
		ConnectionSecretsDBus* conn_secrets_dbus;
		TQValueList<ConnectionSetting*> settings;
		TQString                specific_object;
		bool                   secrets_requested;
};

}

/*
	class Connection
*/
Connection::Connection()
{
	d = new ConnectionPrivate(this);

	NMSettings* nmSettings = NMSettings::getInstance();
	d->obj_path = nmSettings->getObjPathForConnection();

	TQT_DBusConnection conn = TQT_DBusConnection::systemBus();

	if (!registerObject(conn, objectPath()))
		kdError() << "registerobjectpath failed" << endl;

	// get notified whenever NM needs a secret
	connect(d->conn_secrets_dbus, TQT_SIGNAL(SecretsNeeded(const TQString&, const TQStringList&, bool)), this, TQT_SLOT(slotSecretsNeeded(const TQString&, const TQStringList&, bool)));
}

Connection::~Connection()
{
	for (TQValueList<ConnectionSetting*>::Iterator it= d->settings.begin(); it != d->settings.end(); ++it)
	{
		delete (*it);
		*it = NULL;
	}
	delete d;
}

ConnectionSetting*
Connection::getSetting(const TQString& type) const
{
	// find a setting by its type
	for (TQValueList<ConnectionSetting*>::ConstIterator it = d->settings.begin(); it != d->settings.end(); ++it)
	{
		if ((*it)->getType() == type)
			return (*it);
	}
	return NULL;
}

TQValueList<ConnectionSetting*>
Connection::getSettings() const
{
	return d->settings;
}

void
Connection::appendSetting(ConnectionSetting* setting)
{
	// that's our setting now :)
	d->settings.append(setting);
	connect(setting, TQT_SIGNAL(validityChanged()), this, TQT_SLOT(slotSettingValidityChanged()));
}

void
Connection::setSpecificObject(const TQString& obj_path)
{
	d->specific_object = obj_path;
}

TQString
Connection::getSpecificObject() const
{
	return d->specific_object;
}

TQT_DBusObjectPath
Connection::getObjectPath() const
{
	return d->obj_path;
}

TQString
Connection::objectPath() const
{
	return d->obj_path;
}

bool
Connection::isValid() const
{
	bool retval = true;
	// check if every enabled setting is valid
	for (TQValueList<ConnectionSetting*>::ConstIterator it = d->settings.begin(); it != d->settings.end(); ++it)
	{
		if ((*it)->getEnabled())
			retval &= (*it)->isValid();
	}
	return retval;
}

void
Connection::slotSecretsNeeded(const TQString& setting_name, const TQStringList& hints, bool request_new)
{
	printf("Connection::slotSecretsNeeded %s, new: %s\n", setting_name.ascii(), (request_new ? "yes" : "no"));
	kdDebug() << "Connection::slotSecretsNeeded " << setting_name.ascii() << ", new: " << (request_new ? "yes" : "no") << endl;
	ConnectionSetting* setting = getSetting(setting_name);

	// If needed, request new VPN credentials
	if (strcmp("vpn", setting_name.ascii()) == 0) {
		if (vpn_new_credentials_needed == 1) {
			vpn_new_credentials_needed = 0;
			request_new = 1;
		}
	}

	if (!setting)
	{
		// send an error to NM
		d->conn_secrets_dbus->SendGetSecretsReply(NULL);
	}
	else
	{
		if (!request_new && setting->hasSecrets())
		{
			// if the setting has secrets just send them
			d->conn_secrets_dbus->SendGetSecretsReply(setting);
		}
		else
		{
			// NetworkManager asks for new secrets, ask user for new secrets/retry
			d->secrets_requested = true;
			emit SecretsNeeded(this, setting, hints, request_new);
		}
	}
}

void
Connection::slotSecretsProvided(ConnectionSetting* setting)
{
	if (!d->secrets_requested)
		return;

	if (!setting)
	{
		// send all settings to NM
		d->conn_secrets_dbus->SendGetSecretsReply(NULL);
	}
	else
	{
		// if we have the secrets already send them to NM
		d->conn_secrets_dbus->SendGetSecretsReply(setting);
	}
	d->secrets_requested = false;
}

void
Connection::slotSecretsError()
{
	if (!d->secrets_requested)
		return;

	d->conn_secrets_dbus->SendGetSecretsError();
	d->secrets_requested = false;
}

TQT_DBusObjectBase*
Connection::createInterface(const TQString& interfaceName)
{
	// the interfaces are already created, just return the right one
	if (interfaceName == NM_DBUS_IFACE_SETTINGS_CONNECTION)
		return d->conn_dbus;

	if (interfaceName == NM_DBUS_IFACE_SETTINGS_CONNECTION_SECRETS)
		return d->conn_secrets_dbus;

	return NULL;
}

TQString
Connection::getType()
{
	return TQString();
}

void
Connection::slotSettingValidityChanged()
{
	emit validityChanged();
}

void
Connection::slotAboutToBeRemoved()
{
	d->conn_dbus->slotAboutToBeRemoved();
}
void
Connection::slotUpdated()
{
	d->conn_dbus->slotUpdated();
}

void
Connection::updateSettings(Connection* conn)
{
	TQValueList<ConnectionSetting*> settings = conn->getSettings();
	// copy all settings over to the new connection
	for (TQValueList<ConnectionSetting*>::Iterator it = settings.begin(); it != settings.end(); ++it)
	{
		ConnectionSetting* other_setting = *it;
		ConnectionSetting* my_setting = getSetting(other_setting->getType());
		if (my_setting)
		{
			my_setting->fromMap(other_setting->toMap());
			my_setting->fromSecretsMap(other_setting->toSecretsMap(false));
		}
		else
		{
			// should not happen
		}
	}
}

bool
Connection::awaitingSecrets()
{
	return d->secrets_requested;
}

#include "knetworkmanager-connection.moc"
