/***************************************************************************
 *
 * tdenetman-tray.cpp - A NetworkManager frontend for TDE
 *
 * Copyright (C) 2012 Timothy Pearson <kb9vqf@pearsoncomputing.net>
 * 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 <tqimage.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 "tdenetman-wireless_menuitem.h"
#include "tdenetman-wireless_network.h"

using namespace ConnectionSettings;

void WirelessNetworkItem::slotActivate()
{
	TDENetworkDevice* dev = dynamic_cast<TDENetworkDevice*>(hwdevices->findByUniqueID(_dev));
	TDEGlobalNetworkManager* nm = TDEGlobal::networkManager();
	TDENetworkConnectionManager* deviceConnMan = (dev ? dev->connectionManager() : NULL);

	printf("slotActivate\n");
	if (!_dev.isEmpty() && nm && deviceConnMan)
	{
		TDENetworkConnection* conn = nm->findConnectionByUUID(_conn);
		if ( conn )
		{
			kdDebug() << "Activate Connection " << _conn.ascii() << " on Device " << dev->deviceNode().ascii() << endl;
			TDENetworkConnectionStatus::TDENetworkConnectionStatus result = deviceConnMan->initiateConnection(_conn);
// 			if ((result == TDENetworkConnectionStatus::Disconnected)
// 				|| (result == TDENetworkConnectionStatus::Invalid)) {
// 				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()
{
	TDEGlobalNetworkManager* nm = TDEGlobal::networkManager();
	TDENetworkConnection* conn = (nm ? nm->findConnectionByUUID(_conn) : 0);

	TQString security = "";
	if (((_net.getWpaFlags() & TDENetworkWiFiAPFlags::EncryptionFlagsMask) != TDENetworkWiFiAPFlags::None) && ((_net.getRsnFlags() & TDENetworkWiFiAPFlags::EncryptionFlagsMask) != TDENetworkWiFiAPFlags::None)) {
		security = TQString("(%1/%2)").arg(i18n("WPA")).arg(i18n("RSN"));
	}
	else if ((_net.getWpaFlags() & TDENetworkWiFiAPFlags::EncryptionFlagsMask) != TDENetworkWiFiAPFlags::None) {
		security = TQString("(%1)").arg(i18n("WPA"));
	}
	else if ((_net.getRsnFlags() & TDENetworkWiFiAPFlags::EncryptionFlagsMask) != TDENetworkWiFiAPFlags::None) {
		security = TQString("(%2)").arg(i18n("RSN"));
	}

	if (conn && (conn->friendlyName != _net.getDisplaySsid())) {
		return TQString("%2/%1 %3").arg(_net.getDisplaySsid()).arg(conn->friendlyName).arg(security);
	}
	else {
		return TQString("%1 %2").arg(_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 (h - (_border*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", h - (_border*2));
		if (pmLock.size().height() != (h - (_border*2))) {
			TQImage pmLockImg = pmLock.convertToImage();
			pmLockImg = pmLockImg.smoothScale(65535, (h - (_border*2)), TQImage::ScaleMin);
			pmLock.convertFromImage(pmLockImg);
		}
		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", h - (_border*2));
		if (pmAdHoc.size().height() != (h - (_border*2))) {
			TQImage pmAdHocImg = pmAdHoc.convertToImage();
			pmAdHocImg = pmAdHocImg.smoothScale(65535, (h - (_border*2)), TQImage::ScaleMin);
			pmAdHoc.convertFromImage(pmAdHocImg);
		}
		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, TQString dev, WirelessNetwork& net, TQString conn, bool adhoc)
		       : NetworkMenuItem(dev, conn, 0, 0 ), TQCustomMenuItem ()
{
	hwdevices = TDEGlobal::hardwareDevices();

	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, TQString dev, WirelessNetwork& net, bool adhoc)
		       : NetworkMenuItem(dev, NULL, 0, 0 ), TQCustomMenuItem ()
{
	hwdevices = TDEGlobal::hardwareDevices();

	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 "tdenetman-wireless_menuitem.moc"
