/*
 * 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 "dumpfilereader.hpp"

#include <qdebug.h>
#include <qfile.h>
#include <qtimer.h>

namespace IrTouch
{

DumpFileReader::DumpFileReader(const QString &dumpFilePath): mTimer(0), mDump(0)
{
	qDebug() << "DumpFileReader::DumpFileReader( " << dumpFilePath << ");";

	QFile *f = new QFile(dumpFilePath);
	if (f->open(QFile::ReadOnly))
	{
		mDump = new QDataStream(f);
		mTimer = new QTimer(this);
		mTimer->setSingleShot(true);
		connect(mTimer, SIGNAL(timeout()), this, SLOT(emitPacket()));
		readPacket(); // Read first packet from dumpfile;
	}
	else
	{
		qWarning() << "Could not open dump-file" << dumpFilePath;
		delete f;
	}
}

DumpFileReader::~DumpFileReader()
{
	delete mTimer;
	delete mDump->device(); // free file
	delete mDump; // free datastream
}

bool DumpFileReader::isActive() const
{
	return (mDump != 0);
}

void DumpFileReader::readPacket()
{
	Q_ASSERT(mDump); // should never happen
	if (mDump->atEnd())
	{
		qDebug() << "Nothing more to read from dump-file";
		return;
	}
	(*mDump) >> mPacket;
	if (mPacket.isValid())
	{
		if (mLastPacketStamp.isNull()) // Erstes Paket ohne Verzögerung signalisieren
			mLastPacketStamp = mPacket.timestamp();
		int interval = mLastPacketStamp.msecsTo(mPacket.timestamp());
		if (interval >= 0)
		{
			//qDebug() << "Next packet emitted in " << interval;
			mTimer->start(interval);
		}
		else
		{
			qWarning() << "Negative time difference to next packet: " << interval << " ABORTING!";
		}
	}
}

void DumpFileReader::emitPacket()
{
	mLastPacketStamp = mPacket.timestamp();
	emit parsedPacket(mPacket);
	readPacket(); // Read next packet
}

}
