/***************************************************************************
 *
 * 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 <tqevent.h>
#include <tqvbox.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqpixmap.h>
#include <tqpixmapcache.h>
#include <tqpainter.h>
#include <tqstyle.h>
#include <dcopclient.h>
#include <kdebug.h>
#include <kdialogbase.h>
#include <knotifyclient.h>
#include <knotifydialog.h>
#include <tdelocale.h>
#include <kstdguiitem.h>
#include <khelpmenu.h>
#include <kprocess.h>
#include <kiconloader.h>
#include <tdeconfig.h>
#include <tdemessagebox.h>
#include <NetworkManager.h>

#include <tqdbusobjectpath.h>
#include <tqdbuserror.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"

#if !defined(NM_CHECK_VERSION)
#define NM_CHECK_VERSION(x,y,z) 0
#endif

using namespace ConnectionSettings;

void WirelessNetworkItem::slotActivate()
{
	NMProxy* nm = NMProxy::getInstance();
	int id;
	TQT_DBusError err;
	printf("slotActivate\n");
	if (_dev && nm)
	{
		if ( _conn )
		{
			kdDebug() << "Activate Connection " << _conn->getObjectPath().ascii() << " on Device " << _dev->getObjectPath().ascii() << endl;
#if NM_CHECK_VERSION(0,8,992)
			if (!nm->ActivateConnectionAsync(id, "org.freedesktop.NetworkManagerUserSettings", _conn->getObjectPath(), TQT_DBusObjectPath(QCString(_dev->getObjectPath())), _conn->getObjectPath(), err))
#else
			if (!nm->ActivateConnectionAsync(id, NM_DBUS_SERVICE_USER_SETTINGS, _conn->getObjectPath(), TQT_DBusObjectPath(TQCString(_dev->getObjectPath())), _conn->getObjectPath(), err))
#endif
				kdDebug() << "ActivateDevice failed" << endl;

		}
		else
		{
			// TODO: create new connection based upon the network and show the dialog
			printf("New network support not implemented yet\n");
		}
	}
}


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

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

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

void
WirelessNetworkItem::paint (TQPainter *p, const TQColorGroup &/*cg*/, bool highlighted, bool /*enabled*/, int x, int y, int w, int h)
{
	int spacer = 0;
	pbarStrength->setTotalSteps (100);
	pbarStrength->setSizePolicy (TQSizePolicy ((TQSizePolicy::SizeType) 0, (TQSizePolicy::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( TQt::PaletteHighlight, TQt::PaletteHighlight );
	} else {
		p->setPen(parent->palette ().active ().text ());
	}
	p->drawText   (x, y, w, h, AlignLeft | AlignVCenter | DontClip | ShowPrefix, getDisplayText());

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

	if (_adhoc) {
		TQPixmap pmAdHoc = SmallIcon ("computer", TQIconSet::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, TQPixmap::grabWidget (pbarStrength));
}

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

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

	pbarStrength = new TQProgressBar (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, TQIconSet::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 (TQStyle::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 (TQStyle::PM_DefaultFrameWidth))
		_border += 2 * kapp->style ().pixelMetric (TQStyle::PM_DefaultFrameWidth);
	if (_border == 0)
		_border ++;

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

WirelessNetworkItem::WirelessNetworkItem (TQWidget* p, Device* dev, WirelessNetwork& net, bool adhoc)
		       : NetworkMenuItem(dev, NULL, 0, 0 ), TQCustomMenuItem ()
{
	parent       = p;
	_adhoc       = adhoc;
	_net         = net;
	_dev         = dev;

	pbarStrength = new TQProgressBar (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, TQIconSet::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 (TQStyle::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 (TQStyle::PM_DefaultFrameWidth))
		_border += 2 * kapp->style ().pixelMetric (TQStyle::PM_DefaultFrameWidth);
	if (_border == 0)
		_border ++;

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

WirelessNetworkItem::~WirelessNetworkItem ()
{
}



#include "knetworkmanager-wireless_menuitem.moc"
