/***************************************************************************
 *
 * knetworkmanager-tray.cpp - A NetworkManager frontend for KDE
 *
 * Copyright (C) 2005, 2006 Novell, Inc.
 *
 * Author: Timo Hoenig        <thoenig@suse.de>, <thoenig@nouse.net>
 *         Will Stephenson    <wstephenson@suse.de>, <wstephenson@kde.org>
 *         Valentine Sinitsyn <e_val@inbox.ru>
 *         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
 *
 **************************************************************************/

#include <qevent.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qpixmap.h>
#include <qpixmapcache.h>
#include <qpainter.h>
#include <qstyle.h>
#include <dcopclient.h>
#include <kdebug.h>
#include <kdialogbase.h>
#include <knotifyclient.h>
#include <knotifydialog.h>
#include <klocale.h>
#include <kstdguiitem.h>
#include <khelpmenu.h>
#include <kprocess.h>
#include <kiconloader.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <NetworkManager.h>

#include <dbus/qdbusobjectpath.h>
#include <dbus/qdbuserror.h>

#include "knetworkmanager-wireless_menuitem.h"
#include "knetworkmanager-wireless_network.h"
#include "knetworkmanager-connection_setting_info.h"
#include "knetworkmanager-wireless_connection.h"
#include "knetworkmanager-nm_proxy.h"

using namespace ConnectionSettings;

void WirelessNetworkItem::slotActivate()
{
	NMProxy* nm = NMProxy::getInstance();
	int id;
	QDBusError err;
	if (_dev && nm)
	{
		if ( _conn )
		{
			kdDebug() << "Activate Connection " << _conn->getObjectPath().data() << " on Device " << _dev->getObjectPath().ascii() << endl;
			if (!nm->ActivateConnectionAsync(id, NM_DBUS_SERVICE_USER_SETTINGS, _conn->getObjectPath(), QDBusObjectPath(QCString(_dev->getObjectPath())), _conn->getObjectPath(), err))
				kdDebug() << "ActivateDevice failed" << endl;

		}
		else
		{
			// TODO: create new connection based upon the network and show the dialog
			
		}
	}
}


QString WirelessNetworkItem::getDisplayText()
{
	QString security = "";
	if (_net.getWpaFlags() != NM_802_11_AP_SEC_NONE && _net.getRsnFlags() != NM_802_11_AP_SEC_NONE)
		security = QString("(%1/%2)").arg(i18n("WPA")).arg(i18n("RSN"));
	else if (_net.getWpaFlags() != NM_802_11_AP_SEC_NONE)
		security = QString("(%1)").arg(i18n("WPA"));
	else if (_net.getRsnFlags() != NM_802_11_AP_SEC_NONE)
		security = QString("(%2)").arg(i18n("RSN"));

	Info* info = NULL;
	if (_conn)
		info = _conn->getInfoSetting();

	if (info && info->getName() != _net.getDisplaySsid())
		return QString("%2/%1 %3").arg(QString::fromUtf8(_net.getDisplaySsid())).arg(info->getName()).arg(security);
	else
		return QString("%1 %2").arg(QString::fromUtf8(_net.getDisplaySsid())).arg(security);
}

void
WirelessNetworkItem::paint (QPainter *p, const QColorGroup &/*cg*/, bool highlighted, bool /*enabled*/, int x, int y, int w, int h)
{
	int spacer = 0;
	pbarStrength->setTotalSteps (100);
	pbarStrength->setSizePolicy (QSizePolicy ((QSizePolicy::SizeType) 0, (QSizePolicy::SizeType) 0, 0, 0, pbarStrength->sizePolicy ().hasHeightForWidth ()));
	pbarStrength->setFixedHeight (_height - 2);
	pbarStrength->setProgress (_net.getStrength());
	pbarStrength->setPercentageVisible (false);

	if (highlighted) {
		p->setPen(parent->palette ().active ().highlightedText ());
		pbarStrength->setBackgroundMode( Qt::PaletteHighlight, Qt::PaletteHighlight );
	} else {
		p->setPen(parent->palette ().active ().text ());
	}
	p->drawText   (x, y, w, h, AlignLeft | AlignVCenter | DontClip | ShowPrefix, getDisplayText());

	if (_net.isEncrypted()) {
		QPixmap pmLock = SmallIcon ("lock", QIconSet::Automatic);
		p->drawPixmap (parent->sizeHint ().width () - pbarStrength->width () - _space - pmLock.size ().width () - 6, y + _border, pmLock);
		spacer = pmLock.size ().width () + 4;
	}

	if (_adhoc) {
		QPixmap pmAdHoc = SmallIcon ("system", QIconSet::Automatic);
		p->drawPixmap (parent->sizeHint ().width () - pbarStrength->width () - _space - pmAdHoc.size ().width () - spacer - 6, y + _border, pmAdHoc);
	} 
	
	p->drawPixmap (parent->sizeHint ().width () - pbarStrength->width () - _space, y +_border, QPixmap::grabWidget (pbarStrength));
}

QSize
WirelessNetworkItem::sizeHint ()
{
	return QSize (_width, _height);
}

WirelessNetworkItem::WirelessNetworkItem (QWidget* p, Device* dev, WirelessNetwork& net, WirelessConnection* conn, bool adhoc)
		       : NetworkMenuItem(dev, conn, 0, 0 ), QCustomMenuItem ()
{
	parent       = p;
	_adhoc       = adhoc;
	_net         = net;
	_dev         = dev;
	_conn        = conn;

	pbarStrength = new QProgressBar (this->parent, "pbarStrength");
	pbarStrength->hide();
	// TODO make all this neat or at least static
	/* px between pmLock and pbarStrength */
	_space     = 5;

	/* the following code should not be used as teaching material in any kind */
	// set the widget height to that of a small icon
	_widgetHeight = SmallIcon (NULL, QIconSet::Automatic).height ();
	// figure out the height of the text
	_textHeight = kapp->fontMetrics ().size (AlignLeft | AlignVCenter | DontClip | ShowPrefix, _net.getDisplaySsid()).height ();
	// the item is height of the text plus the default frame width
	_height = _textHeight + kapp->style ().pixelMetric (QStyle::PM_DefaultFrameWidth);
	/* _height needs to be at least the height of a SmallIcon plus a border of one px (top & bottom)*/
	if (_height < _widgetHeight) {
		_height = _widgetHeight + 2;
	}

	/* border required for pmLock and pbarStrength */
	_border = 1;
	if (_border == kapp->style ().pixelMetric (QStyle::PM_DefaultFrameWidth))
		_border += 2 * kapp->style ().pixelMetric (QStyle::PM_DefaultFrameWidth);
	if (_border == 0)
		_border ++;

	_width =  kapp->fontMetrics().size(AlignLeft | AlignVCenter | DontClip | ShowPrefix, getDisplayText()).width(); /* essid */
	_width += SmallIcon (NULL, QIconSet::Automatic).width ();                                             /* pmLock */
	_width += _space;                                                                                     /* pmLock <-> pbarStrength */
	_width += 100;                                                                                        /* pbarStrength */
	_width += _space;                                                                                     /* pbarStrength -> contextMenu */
}

WirelessNetworkItem::~WirelessNetworkItem ()
{
}



#include "knetworkmanager-wireless_menuitem.moc"
