/*
    knetd, KDE Network Daemon

    Copyright (c) 2005 by Engin AYDOGAN		<engin @ bzzzt.biz>

    *************************************************************************
    *                                                                       *
    * 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.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "sysfsclass.h"

#include <kdebug.h>

SYSFSClass*
SYSFSClass::build( const QString& name, int freq )
{
	sysfs_class* cl = sysfs_open_class( name.ascii() );
	if( cl )
	{
		return new SYSFSClass( cl, freq );
	}
	else
	{
		return NULL;
	}
}

SYSFSClass::SYSFSClass( sysfs_class* cl, int freq )
 : m_class( cl ), m_name( cl->name )
{
	startTimer( freq );
}

SYSFSClass::~SYSFSClass()
{
	sysfs_close_class( m_class );
}

QStringList
SYSFSClass::probe()
{
	QStringList devList;
	dlist* list = 0L;
	sysfs_class_device* device = 0L;
	// there is no refresh device list function in libsysfs *sigh*
	sysfs_close_class( m_class );
	m_class = sysfs_open_class( m_name.ascii() );
	list = sysfs_get_class_devices( m_class );
	if( list )
	{
		// iterate through the device list and store them in a QStrinList
		dlist_for_each_data( list, device, sysfs_class_device )
		{
			devList.push_back( device->name );
		}
	}
	else	
	{
		kdError() << k_funcinfo << "Could not fetch device list." << endl;
	}
	return devList;
}

QStringList
SYSFSClass::devices() const
{
	return m_devList;
}

void
SYSFSClass::timerEvent( QTimerEvent* )
{
	// fetch current device list
	QStringList newList = probe();
	// backup
	QStringList t_newList = newList;
	// backup the device list we got already
	QStringList t_deviceList = m_devList;

	QStringList::Iterator it;

	// remove each current device from the list we have
	// the remaining items are the devices not available anymore (they're removed)
	for( it = newList.begin(); it != newList.end(); ++it )
	{
		t_deviceList.remove( *it );
	}

	// remove the devices we already have in our list from the new devices list
	// the ramaining items are the devices avaiable just now (they're newly added)
	for( it = m_devList.begin(); it != m_devList.end(); ++it )
	{
		t_newList.remove( *it );
	}

	// iterate through removed devices and notify the user via SystemTray
	for( it = t_deviceList.begin(); it != t_deviceList.end(); ++it )
	{
		emit deviceRemoved( (*it) );
	}

	// iterate through the newly added devices and notify the user via SystemTray
	for( it = t_newList.begin(); it != t_newList.end(); ++it )
	{
		emit deviceFound( (*it) );
	}

	// store new device list as our list.
	m_devList = newList;
}

#include "sysfsclass.moc"
