/*
 * Copyright 2009-2010  Stefan Gehn <stefan@srcbox.net>
 * 
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "TouchThread.hpp"
#include "SerialReader.hpp"
#include "dumpfilereader.hpp"
#include "Decoder.hpp"
#include "settings.hpp"

#include <qfile.h>
#include <qmetatype.h>

namespace IrTouch
{

TouchThread::TouchThread(const QString &inputFilePath) :
	QThread(), mPacketReader(0), mDecoder(0), mInputFilePath(inputFilePath), mDumpStream(0)
{
	qRegisterMetaType<IrTouch::Packet> ("IrTouch::Packet");
  qRegisterMetaType<IrTouch::TouchData> ("IrTouch::TouchData");
}


void TouchThread::run()
{
	if (mInputFilePath.isEmpty())
	{
		mPacketReader = new SerialReader();

		if (Settings::self()->record() && mPacketReader->isActive())
		{
			QString filePath = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz") +
												 QString::fromUtf8(".dump");
			qDebug() << "TouchThread; Recording incoming packet data to dumpfile" << filePath;
			QFile *dumpFile = new QFile(filePath);
			if (!dumpFile->open(QIODevice::WriteOnly))
			{
				qWarning() << "TouchThread; Could not open dumpfile" << filePath << endl;
				delete dumpFile;
			}
			else
			{
				mDumpStream = new QDataStream(dumpFile);
			}
		}

	}
	else
	{
		mPacketReader = new DumpFileReader(mInputFilePath);
	}

	qDebug() << "TouchThread; creating packet-decoder";
	mDecoder = new Decoder();
	QObject::connect(mPacketReader, SIGNAL(parsedPacket(IrTouch::Packet)),
		this, SLOT(handlePacket(IrTouch::Packet)));

	qDebug() << "TouchThread; entering event-loop";
	exec();
	qDebug() << "TouchThread; shutting down";

	delete mPacketReader;
	mPacketReader = 0;

	delete mDecoder;
	mDecoder = 0;

	if (mDumpStream)
	{
		delete mDumpStream->device();
		delete mDumpStream;
	}
}


void TouchThread::handlePacket(IrTouch::Packet packet)
{
  //qDebug() << "TouchThread::handlePacket(), calling decoder...";
	if (mDumpStream)
		*mDumpStream << packet;

	mDecoder->decodePacket(packet);
	const TouchData &data = mDecoder->touchData();
  //qDebug() << "TouchThread::handlePacket() emitting dataDecoded() with " << &data << data;
  emit dataDecoded(data);
}

}

#include "moc_TouchThread.cpp"
