/*
 * Application.cpp
 *
 *  Created on: 18.07.2011
 *      Author: stefan.detter
 */

#include "Application.h"

#include <QVariant>

#include <QrfeReaderManager>
#include <QrfeReaderInterface>

#include "Reader.h"

Application::Application( QrfeReaderManager* manager, QObject* parent )
	: QObject(parent)
	, QrfeTraceModule("Application")
	, m_manager(manager)
{
	connect(m_manager,		SIGNAL(gotReader(QrfeReaderInterface*)),
			this,			  SLOT(readerAttachedSlot(QrfeReaderInterface*)));
}

Application::~Application()
{
	foreach(Reader* reader, m_toDelete)
		delete reader;
}

QrfeReaderManager*	Application::readerManager() const
{
	return m_manager;
}

QList<QString> Application::readerList() const
{
	return m_reader.keys();
}

Reader*	Application::reader(QString readerId) const
{
	return m_reader.value(readerId);
}


void Application::readerAttachedSlot ( QrfeReaderInterface* readerIf )
{
	Reader* r = new Reader(readerIf);
	m_reader.insert(r->readerId(), r);
	emit readerAttached(r);

	QObject::connect(r, SIGNAL(lostConnection()), 		this, SLOT(readerLostConnectionSlot()));
	QObject::connect(r, SIGNAL(requestForDelete()), 	this, SLOT(readerDeleteRequestSlot()));

	QList<QVariant> params;
	params.append((uint)1500);
	emit appendGlobalJob(JOB_WaitForSpeciifedTime, params);

	params.clear();
	params.append(r->readerId());
	emit appendGlobalJob(JOB_CheckReaderForUpdates, params);
}

void Application::readerLostConnectionSlot()
{
	trc(1, "Lost connection to reader");
	Reader* reader = qobject_cast<Reader*>(sender());

	if(!m_reader.values().contains(reader))
		return;
 
	m_reader.remove(reader->readerId());

	emit readerLost();
}

void Application::readerDeleteRequestSlot()
{
	trc(1, "Reader requests to be deleted");
	Reader* reader = qobject_cast<Reader*>(sender());

	if(!m_reader.values().contains(reader))
		return;

	m_reader.remove(reader->readerId());

	emit readerLost();
}


