/***************************************************************************
 *
 * tdenetman-devicestore_dbus.cpp - A NetworkManager frontend for TDE
 *
 * Copyright (C) 2005, 2006 Novell, Inc.
 *
 * Author: Timo Hoenig        <thoenig@suse.de>, <thoenig@nouse.net>
 *         Valentine Sinitsyn <e_val@inbox.ru>
 *
 * 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 <tqwidget.h>
#include <tqlineedit.h>
#include <tqlayout.h>
#include <tqlistview.h>
#include <tqtimer.h>
#include <tqcheckbox.h>

#include <tdelistview.h>
#include <klineedit.h>
#include <tdelistviewsearchline.h>
#include <kiconloader.h>
#include <tdeglobal.h>
#include <kpushbutton.h>
#include <tdelocale.h>

#include "tdenetman-connection_setting_widget_interface.h"
#include "tdenetman-connection_setting_wireless_widget.h"
#include "tdenetman-wireless_manager.h"

using namespace ConnectionSettings;

class NetworkListViewItem : public TDEListViewItem
{
	public:

	NetworkListViewItem(TQListView* parent, WirelessNetwork& net)
		: TDEListViewItem(parent, net.getDisplaySsid(), TQString("%1\%").arg(net.getStrength()))
		, _net(net)
	{
		TQ_UINT8 strength = net.getStrength();
		if (strength > 80) {
			setPixmap(1, TDEGlobal::iconLoader()->loadIcon("nm_signal_100", TDEIcon::Small));
		}
		else if (strength > 55) {
			setPixmap(1, TDEGlobal::iconLoader()->loadIcon("nm_signal_75", TDEIcon::Small));
		}
		else if (strength > 30) {
			setPixmap(1, TDEGlobal::iconLoader()->loadIcon("nm_signal_50", TDEIcon::Small));
		}
		else if (strength > 5) {
			setPixmap(1, TDEGlobal::iconLoader()->loadIcon("nm_signal_25", TDEIcon::Small));
		}
		else {
			setPixmap(1, TDEGlobal::iconLoader()->loadIcon("nm_signal_00", TDEIcon::Small));
		}

		if (net.isEncrypted()) {
			setPixmap(2, TDEGlobal::iconLoader()->loadIcon("system-lock-screen", TDEIcon::Small));
		}

		setText(3, TQString("%1").arg(net.getAPCount()));
	}

	WirelessNetwork _net;
};

WirelessWidgetImpl::WirelessWidgetImpl(TDENetworkConnection* conn, bool new_conn, TQByteArray preselect_ssid, TQWidget* parent, const char* name, WFlags fl)
	: WidgetInterface(parent, name, fl)
{
	_parentdialog = dynamic_cast<ConnectionSettingsDialogImpl*>(parent);

	_wireless_setting = dynamic_cast<TDEWiFiConnection*>(conn);
	_info_setting = dynamic_cast<TDEWiFiConnection*>(conn);
	_security_setting = dynamic_cast<TDEWiFiConnection*>(conn);
	_hasName = !_info_setting->friendlyName.isEmpty();
	_new_conn = new_conn;
	_preselect_ssid = preselect_ssid;

	TQVBoxLayout* layout = new TQVBoxLayout(this, 1, 1);
	_mainWid = new ConnectionSettingWirelessWidget(this);
	layout->addWidget(_mainWid);

	// FIXME hide this button until it is implemented
	_mainWid->pbExpert->hide();

	Init();
}

void
WirelessWidgetImpl::Init()
{
	TQVBoxLayout* layout = new TQVBoxLayout(_mainWid->framePlaceholder, 1, 1);
	_searchLine = new TDEListViewSearchLineWidget(_mainWid->lvEssids, _mainWid->framePlaceholder);
	layout->addWidget(_searchLine);

	connect(_mainWid->txtEssid, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(slotEssidChanged(const TQString&)));
	connect(_mainWid->lvEssids, TQ_SIGNAL(doubleClicked(TQListViewItem*, const TQPoint&, int)), this, TQ_SLOT(slotEssidDoubleClicked(TQListViewItem*, const TQPoint&, int)) );
	connect(_mainWid->lvEssids, TQ_SIGNAL(selectionChanged(TQListViewItem*)), this, TQ_SLOT(slotEssidChanged(TQListViewItem*)));

	if (!_new_conn)
	{
		_mainWid->chkAutoRefresh->hide();
		_mainWid->lvEssids->hide();
		_searchLine->hide();
	}
}

void
WirelessWidgetImpl::Activate()
{
	// Fill in all available networks from all devices
	// get all aps from all devices grouped together using the ssid
	TQValueList<WirelessNetwork> nets = WirelessManager::getWirelessNetworks(0, WirelessNetwork::MATCH_SSID);

	_mainWid->lvEssids->clear();

	for (TQValueList<WirelessNetwork>::Iterator it = nets.begin(); it != nets.end(); ++it)
	{
		TDEListViewItem* item = new NetworkListViewItem(_mainWid->lvEssids, (*it));

		_mainWid->lvEssids->insertItem(item);
	}

	// FIXME, if essid contains unprintable characters show the essid in hex
	_mainWid->txtEssid->setText(_wireless_setting->SSID);

	if (!_preselect_ssid.isNull()) {
		TQListViewItemIterator it(_mainWid->lvEssids);
		while (it.current()) {
			NetworkListViewItem* item = dynamic_cast<NetworkListViewItem*>(it.current());
			if (item) {
				if (item->_net.getSsid() == _preselect_ssid) {
					_mainWid->lvEssids->setSelected(item, true);
					slotEssidChanged(item);
				}
			}
			++it;
		}
	}
}

void WirelessWidgetImpl::slotEssidChanged(TQListViewItem* item)
{
	NetworkListViewItem* net_item = dynamic_cast<NetworkListViewItem*>(item);
	if (net_item)
	{
		// update the settingsobject
		updateEssid(net_item->_net.getSsid());

		// update the textbox to match the selected essid
		_mainWid->txtEssid->setText(net_item->_net.getDisplaySsid());
	}

	if (_parentdialog) _parentdialog->slotEnableButtons();	// Update lockouts
}

void
WirelessWidgetImpl::slotEssidDoubleClicked(TQListViewItem* item, const TQPoint& /*p*/, int /*i*/)
{
	NetworkListViewItem* net_item = dynamic_cast<NetworkListViewItem*>(item);
	if (net_item)
	{
		updateEssid(net_item->_net.getSsid());
		// essid selected with double click -> goto the next setting
		emit next();
	}

	if (_parentdialog) _parentdialog->slotEnableButtons();	// Update lockouts
}


void
WirelessWidgetImpl::slotEssidChanged(const TQString& new_essid)
{
	/* set the newly entered essid */
	/* FIXME perhaps local8Bit is better? */
	/* FIXME allow entering essid in hex */
	/* FIXME select the appropriate essid in the list too */

	TQByteArray essid(new_essid.utf8());

	// remove trailing \0
	essid.resize(essid.size() - 1);

	updateEssid(essid);

	if (_parentdialog) _parentdialog->slotEnableButtons();	// Update lockouts
}

void
WirelessWidgetImpl::updateEssid(const TQByteArray& essid)
{
	_wireless_setting->SSID = essid;

	if (!_hasName)
	{
		// the connection has no name yet -> just take the essid for it
		_info_setting->friendlyName = TQString(essid);
		if (_info_setting->friendlyName == "") {
			_info_setting->friendlyName = "<" + i18n("hidden") + ">";
		}
	}

	if (_parentdialog) _parentdialog->slotEnableButtons();	// Update lockouts
}

TQByteArray WirelessWidgetImpl::byteArrayFromHexString(const TQCString& str)
{
	char c[2];
	TQByteArray arr(str.length() - 1);
	TQTextStream stream(str, IO_ReadOnly);

	stream.setf(TQTextStream::hex);
	stream.setf(TQTextStream::left);
	stream.width(2);
	stream.fill('0');

	// 0x
	stream.readRawBytes(c, 2);

	for (uint i = 0; i < (str.length()-1)/2; ++i)
	{
		stream.readRawBytes(c, 2);
		TQString hex;
		hex += "0x";
		hex += c[0];
		hex += c[1];
		arr[i] = (unsigned char)hex.toShort();
	}
	return arr;
}

TQString WirelessWidgetImpl::hexStringFromByteArray(const TQByteArray& bytes)
{
	TQString tmp;
	TQTextStream stream(&tmp, IO_ReadWrite);
	stream.setf(TQTextStream::hex);
	stream.setf(TQTextStream::left);
	stream.width(2);
	stream.fill('0');

	stream << "0x" ;
	for (uint i = 0; i < bytes.size(); ++i)
	{
		stream << static_cast<unsigned char>(bytes[i]);
	}
	return tmp;
}

#include "tdenetman-connection_setting_wireless_widget.moc"
