/***************************************************************************
 *
 * knetworkmanager-devicestore_dbus.cpp - A NetworkManager frontend for KDE
 *
 * 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 <qwidget.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qlistview.h>

#include <klistview.h>
#include <klineedit.h>
#include <klistviewsearchline.h>
#include <kiconloader.h>
#include <kglobal.h>
#include <kpushbutton.h>

#include "knetworkmanager-connection.h"
#include "knetworkmanager-connection_setting_widget_interface.h"
#include "knetworkmanager-connection_setting_wireless_widget.h"
#include "knetworkmanager-connection_setting_wireless.h"
#include "knetworkmanager-connection_setting_wireless_security.h"
#include "knetworkmanager-connection_setting_info.h"
#include "knetworkmanager-wireless_network.h"
#include "knetworkmanager-wireless_manager.h"

using namespace ConnectionSettings;

class NetworkListViewItem : public KListViewItem
{
	public:

	NetworkListViewItem(QListView* parent, WirelessNetwork& net)
		: KListViewItem(parent, QString::fromUtf8(net.getDisplaySsid()), QString("%1\%").arg(net.getStrength()))
		, _net(net)
	{
		Q_UINT8 strength = net.getStrength();
		if (strength > 80)
			setPixmap(1, KGlobal::iconLoader()->loadIcon("nm_signal_100", KIcon::Small));
		else if (strength > 55)
			setPixmap(1, KGlobal::iconLoader()->loadIcon("nm_signal_75", KIcon::Small));
		else if (strength > 30)
			setPixmap(1, KGlobal::iconLoader()->loadIcon("nm_signal_50", KIcon::Small));
		else if (strength > 5)
			setPixmap(1, KGlobal::iconLoader()->loadIcon("nm_signal_25", KIcon::Small));
		else
			setPixmap(1, KGlobal::iconLoader()->loadIcon("nm_signal_00", KIcon::Small));

		if (net.isEncrypted())
			setPixmap(2, KGlobal::iconLoader()->loadIcon("lock", KIcon::Small));
	}

	WirelessNetwork _net;
};

WirelessWidgetImpl::WirelessWidgetImpl(Connection* conn, bool new_conn, QWidget* parent, const char* name, WFlags fl)
	: WidgetInterface(parent, name, fl)
{
	_wireless_setting = dynamic_cast<Wireless*> (conn->getSetting(NM_SETTING_WIRELESS_SETTING_NAME));
	_info_setting = dynamic_cast<Info*> (conn->getSetting(NM_SETTING_CONNECTION_SETTING_NAME));
	_security_setting = dynamic_cast<WirelessSecurity*> (conn->getSetting(NM_SETTING_WIRELESS_SECURITY_SETTING_NAME));
	_hasName = !_info_setting->getName().isEmpty();
	_new_conn = new_conn;

	QVBoxLayout* layout = new QVBoxLayout(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()
{
	QVBoxLayout* layout = new QVBoxLayout(_mainWid->framePlaceholder, 1, 1);
	_searchLine = new KListViewSearchLineWidget(_mainWid->lvEssids, _mainWid->framePlaceholder);
	layout->addWidget(_searchLine);

	connect(_mainWid->txtEssid, SIGNAL(textChanged(const QString&)), this, SLOT(slotEssidChanged(const QString&)));
	connect(_mainWid->lvEssids, SIGNAL(doubleClicked(QListViewItem*, const QPoint&, int)), this, SLOT(slotEssidDoubleClicked(QListViewItem*, const QPoint&, int)) );
	connect(_mainWid->lvEssids, SIGNAL(selectionChanged(QListViewItem*)), this, SLOT(slotEssidChanged(QListViewItem*)));

	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
	QValueList<WirelessNetwork> nets = WirelessManager::getWirelessNetworks(0, WirelessNetwork::MATCH_SSID);

	_mainWid->lvEssids->clear();

	for (QValueList<WirelessNetwork>::Iterator it = nets.begin(); it != nets.end(); ++it)
	{
		KListViewItem* 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->getEssid());
}

void WirelessWidgetImpl::slotEssidChanged(QListViewItem* 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());
	}
}

void
WirelessWidgetImpl::slotEssidDoubleClicked(QListViewItem* item, const QPoint& /*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();
	}
}


void
WirelessWidgetImpl::slotEssidChanged(const QString& 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 */

	QByteArray essid(new_essid.utf8());

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

	updateEssid(essid);
}

void
WirelessWidgetImpl::updateEssid(const QByteArray& essid)
{
	_wireless_setting->setEssid(essid);

	if (!_hasName)
	{
		// the connection has no name yet -> just take the essid for it
		_info_setting->setName(essid);
	}
}

QByteArray WirelessWidgetImpl::byteArrayFromHexString(const QCString& str)
{
	char c[2];
	QByteArray arr(str.length() - 1);
	QTextStream stream(str, IO_ReadOnly);

	stream.setf(QTextStream::hex);
	stream.setf(QTextStream::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);
		QString hex;
		hex += "0x";
		hex += c[0];
		hex += c[1];
		arr[i] = (unsigned char)hex.toShort();
	}
	return arr;
}

QString WirelessWidgetImpl::hexStringFromByteArray(const QByteArray& bytes)
{
	QString tmp;
	QTextStream stream(&tmp, IO_ReadWrite);
	stream.setf(QTextStream::hex);
	stream.setf(QTextStream::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 "knetworkmanager-connection_setting_wireless_widget.moc"
