/*
 * TimeTrackController.cpp
 *
 *  Created on: 03.02.2010
 *      Author: stefan.detter
 */

#include "TimeTrackController.h"

#include <QCoreApplication>
#include <QFile>
#include <QDateTime>
#include <QStringList>
#include <QFileDialog>
#include <QDesktopServices>

//#include <QDialog>
//#include <QVBoxLayout>
//#include <qwt_plot.h>
//#include <qwt_plot_curve.h>
//#include <qwt_plot_grid.h>
//#include <qwt_legend.h>

#include <QrfeReaderInterface>

#include "../../../Cache.h"
#include "../../../def.h"

#if QT_VERSION > 0x050000	
	#include <QStandardPaths>
	#define STORAGE_SERVICE		QStandardPaths
	#define STORAGE_FUNCTION	writableLocation
#else
	#include <QDesktopServices>
	#define STORAGE_SERVICE		QDesktopServices
	#define STORAGE_FUNCTION	storageLocation
#endif

TimeTrackController::TimeTrackController(QWidget* mainWidget, Application* app, QObject* parent)
	: TagReadHandlerBase(mainWidget, app, parent)
	, m_trackingFile(0)
{
    m_rssiDefSize		= 0;
    m_memoryDefSize		= 0;
    m_triggerDefSize	= 0;
    m_antennaDefSize	= 0;
    m_frequencyDefSize	= 0;
    m_batteryDefSize	= 0;
    m_stateDefSize 		= 0;

	m_lastRecordPath = Cache::d.value(RECORD_LAST_USED_FILEPATH, STORAGE_SERVICE::STORAGE_FUNCTION(STORAGE_SERVICE::DesktopLocation)).toString();
}

TimeTrackController::~TimeTrackController()
{

}

void TimeTrackController::doTracking ( bool on )
{
	if(on == true)
	{
		m_trackingFile = 0;

		QString fileName = m_lastRecordPath + "/Record_" + QDateTime::currentDateTime().toString("yyyy_MM_dd-hh_mm") + ".csv";
	    fileName = QFileDialog::getSaveFileName(m_mainWidget, tr("Record"), fileName, tr("CSV-File (*.csv)"));

	    if(fileName.isNull())
	    {
	    	on = false;
	    	return;
	    }

	    m_rssiDefSize		= 0;
	    m_memoryDefSize		= 0;
	    m_triggerDefSize	= 0;
	    m_antennaDefSize	= 0;
	    m_frequencyDefSize	= 0;
	    m_batteryDefSize	= 0;
	    m_infoPosition.clear();


		m_trackingFile = new QFile(fileName);
		m_trackingFile->open(QIODevice::WriteOnly);

//		m_history.clear();
//		m_startTime.start();
	}
	else
	{
		if(m_trackingFile == 0)
			return;

		m_trackingFile->close();
		m_trackingFile->deleteLater();

//		if(m_history.keys().size() >= 1)
//		{
//			QDialog* dialog = new QDialog();
//			dialog->setLayout(new QVBoxLayout(dialog));
//			QwtPlot* plot = new QwtPlot(dialog);
//			dialog->layout()->addWidget(plot);
//
//			QwtPlotGrid* grid = new QwtPlotGrid();
//		    grid->enableXMin(true);
//		    grid->enableYMin(true);
//		    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
//		    grid->setMinPen(QPen(Qt::gray, 0 , Qt::DotLine));
//			grid->attach(plot);
//
//			plot->insertLegend(new QwtLegend(dialog), QwtPlot::BottomLegend);
//
//			for(int j = 0; j < m_history.keys().size(); j++)
//			{
//				QVector<double> time;
//				QVector<double> value;
//
//				QString epc = m_history.keys().at(j);
//				QMap<uint, uchar> epc_history = m_history.value(epc);
//				for(int i = 0; i < epc_history.keys().size(); i++)
//				{
//					time  << epc_history.keys().at(i);
//					value << epc_history.value(epc_history.keys().at(i));
//				}
//
//				QwtPlotCurve* curve = new QwtPlotCurve(epc);
//				curve->attach(plot);
//
//				curve->setData(time.data(), value.data(), time.size());
//			}
//
//			plot->replot();
//
//
//			dialog->exec();
//
//			delete dialog;
//		}

	}
	handlingActivated(on);
}


void TimeTrackController::tagEvent(const TagEvent& event)
{
	if(!m_handlingOn)
		return;


	QStringList data;

	data << QDateTime::currentDateTime().toString("dd.MM.yyyy;hh:mm:ss;zzz");
	data << event.readerId();
	data << event.readerName();
	data << event.tagId();

	QStringList rssi, memory, trigger, antenna, frequency, state, battery;

	QList<QVariant> infos = event.getInformations();
	foreach(QVariant v, infos)
	{
		if(v.canConvert<RSSI_Information>())
		{
			RSSI_Information info = v.value<RSSI_Information>();

			rssi << QString::number(info.percent()) + "%";
			for(int i = 0; i < info.getChannels().size() - 1; i++)
			{
				rssi << QString::number(info.getChannels().at(i).value);
			}
			//m_history[epc].insert(m_startTime.elapsed(), rssiPercent.at(0));
			m_rssiDefSize = rssi.size();

			if(!m_infoPosition.contains(RSSI_INFORMATION))
				m_infoPosition << RSSI_INFORMATION;
		}
		else if(v.canConvert<MEMORY_Information>())
		{
			MEMORY_Information info = v.value<MEMORY_Information>();

			memory << info.memBankName();
			memory << QString::number(info.memBank());
			memory << QString::number(info.memAddr());
			memory << info.memData().toHex();

			m_memoryDefSize = memory.size();

			if(!m_infoPosition.contains(MEMORY_INFORMATION))
				m_infoPosition << MEMORY_INFORMATION;
		}
		else if(v.canConvert<TRIGGER_Information>())
		{
			TRIGGER_Information info = v.value<TRIGGER_Information>();

			trigger << QString::number(info.triggerId());
			trigger << info.triggerName();

			m_triggerDefSize = trigger.size();

			if(!m_infoPosition.contains(TRIGGER_INFORMATION))
				m_infoPosition << TRIGGER_INFORMATION;
		}
		else if(v.canConvert<ANTENNA_Information>())
		{
			ANTENNA_Information info = v.value<ANTENNA_Information>();

			antenna << "Antenna #" + QString::number(info.antennaId());

			m_antennaDefSize = antenna.size();

			if(!m_infoPosition.contains(ANTENNA_INFORMATION))
				m_infoPosition << ANTENNA_INFORMATION;
		}
		else if(v.canConvert<FREQUENCY_Information>())
		{
			FREQUENCY_Information info = v.value<FREQUENCY_Information>();

			frequency << QString::number(info.frequency()) + "MHz";

			m_frequencyDefSize = frequency.size();

			if(!m_infoPosition.contains(FREQUENCY_INFORMATION))
				m_infoPosition << FREQUENCY_INFORMATION;
		}
		else if(v.canConvert<STATE_Information>())
		{
			STATE_Information info = v.value<STATE_Information>();

			state << QString("%1").arg(info.state(), 4, 16, QChar('0'));
			state << info.stateName();

			m_stateDefSize = state.size();

			if(!m_infoPosition.contains(STATE_INFORMATION))
				m_infoPosition << STATE_INFORMATION;
		}
		else if(v.canConvert<BATTERY_Information>())
		{
			BATTERY_Information info = v.value<BATTERY_Information>();

			battery << QString::number(info.battery()) + "%";

			m_batteryDefSize = battery.size();

			if(!m_infoPosition.contains(BATTERY_INFORMATION))
				m_infoPosition << BATTERY_INFORMATION;
		}
	}

	if(m_infoPosition.contains(RSSI_INFORMATION))
		for(int i = rssi.size(); i < m_rssiDefSize; i++ )
			rssi << "";
	if(m_infoPosition.contains(MEMORY_INFORMATION))
		for(int i = memory.size(); i < m_memoryDefSize; i++ )
			memory << "";
	if(m_infoPosition.contains(TRIGGER_INFORMATION))
		for(int i = trigger.size(); i < m_triggerDefSize; i++ )
			trigger << "";
	if(m_infoPosition.contains(ANTENNA_INFORMATION))
		for(int i = antenna.size(); i < m_antennaDefSize; i++ )
			antenna << "";
	if(m_infoPosition.contains(FREQUENCY_INFORMATION))
		for(int i = frequency.size(); i < m_frequencyDefSize; i++ )
			frequency << "";
	if(m_infoPosition.contains(STATE_INFORMATION))
		for(int i = state.size(); i < m_stateDefSize; i++ )
			state << "";
	if(m_infoPosition.contains(BATTERY_INFORMATION))
		for(int i = battery.size(); i < m_batteryDefSize; i++ )
			battery << "";

	for(int i = 0; i < m_infoPosition.size(); i++)
	{
		switch(m_infoPosition.at(i))
		{
		case RSSI_INFORMATION:
			data << rssi; break;
		case MEMORY_INFORMATION:
			data << memory; break;
		case TRIGGER_INFORMATION:
			data << trigger; break;
		case ANTENNA_INFORMATION:
			data << antenna; break;
		case FREQUENCY_INFORMATION:
			data << frequency; break;
		case STATE_INFORMATION:
			data << state; break;
		case BATTERY_INFORMATION:
			data << battery; break;
		default:
			break;
		}
	}

	m_trackingFile->write(data.join(";").toLatin1());
	m_trackingFile->write("\n");
	m_trackingFile->flush();
}
