/*
 * QrfeTraceWidget.cpp
 *
 *  Created on: 15.02.2011
 *      Author: stefan.detter
 */

#include "../inc/QrfeTraceModel.h"

#include <QAbstractItemView>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>

#include <QApplication>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>

#include <QrfeTrace>

#include "../inc/QrfeGuiLibGlobal.h"

QrfeTraceModel::QrfeTraceModel(QObject* parent)
	: QObject(parent)
{
	m_model = new QStandardItemModel(this);
	m_model->setColumnCount(5);

	m_proxy = new QSortFilterProxyModel(this);
	m_proxy->setSourceModel(m_model);

	setHeader();

	m_seperator = QChar(' ');
	m_enabled = false;
}

QrfeTraceModel::~QrfeTraceModel()
{

}

void QrfeTraceModel::setView(QAbstractItemView* view)
{
	m_view = view;
	m_view->setModel(m_proxy);
}

void QrfeTraceModel::setSeperator( QChar sep )
{
	m_seperator = sep;
}

void QrfeTraceModel::setEnabled ( bool enabled )
{
	if(enabled)
	{
		if(m_enabled)
			return;

		connect(QrfeTrace::getInstance(), 		SIGNAL(traceSignal(const QString&)),
				this, 							  SLOT(trace(const QString&)), Qt::DirectConnection );
		m_enabled = true;
	}
	else
	{
		if(!m_enabled)
			return;

		disconnect(QrfeTrace::getInstance(), 		SIGNAL(traceSignal(const QString&)),
					this, 							  SLOT(trace(const QString&)));
		m_enabled = false;
	}
}


void QrfeTraceModel::trace( const QString& message)
{
	QStringList list = message.split(m_seperator, QString::SkipEmptyParts);//split(QRegExp("(\\s+)"));

	QString time, component, thread, msg;

	if(m_seperator == ' ' && list.size() >= 5)
	{
		time 		= list.at(0);
		component 	= list.at(1);
		thread	 	= list.at(2);
		list = list.mid(4, list.size());
		msg		 	= list.join(" ");
	}
	else if(m_seperator == ';' && list.size() >= 4)
	{
		time 		= list.at(0);
		component 	= list.at(1);
		thread	 	= list.at(2);
		list = list.mid(3, list.size());
		msg		 	= list.join(" ");
	}
	else
	{
		time 		= "";
		component 	= "";
		thread 		= "";
		msg 		= message;
	}

	QList<QStandardItem*> items;
	items << new QStandardItem(QString("%1").arg(m_model->rowCount(), 8, 10, QChar('0')));
	items << new QStandardItem(time); // Time
	items << new QStandardItem(component); // Component
	items << new QStandardItem(thread); // Thread
	items << new QStandardItem(msg);

	items[0]->setTextAlignment(Qt::AlignCenter);
	items[1]->setTextAlignment(Qt::AlignCenter);
	items[2]->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
	items[3]->setTextAlignment(Qt::AlignCenter);
	items[4]->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);

	if(thread != "")
	{
		items[0]->setForeground(Qt::white);
		items[1]->setForeground(Qt::white);
		items[2]->setForeground(Qt::white);
		items[3]->setForeground(Qt::white);
		items[4]->setForeground(Qt::white);

		if(!m_threadColors.contains(thread)){
			m_threadColors.insert(thread, QrfeGlobal::getAlternatingDarkColors(m_threadColors.size()) );
		}

		QColor c = m_threadColors.value(thread);

		items[0]->setBackground(c);
		items[1]->setBackground(c);
		items[2]->setBackground(c);
		items[3]->setBackground(c);
		items[4]->setBackground(c);
	}

	if( msg.startsWith("WARNING") )
	{
		QIcon icon = QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning);
		items[0]->setIcon(icon);
		items[4]->setIcon(icon);
	}
	else if( msg.startsWith("ERROR") || msg.startsWith("FATAL") )
	{
		QIcon icon = QApplication::style()->standardIcon(QStyle::SP_MessageBoxCritical);
		items[0]->setIcon(icon);
		items[4]->setIcon(icon);
	}

	m_model->insertRow(0,items);
}

void QrfeTraceModel::clear()
{
	m_model->clear();
	m_threadColors.clear();
	setHeader();
}

void QrfeTraceModel::exportTrace()
{
	QString homePath = QDir::homePath();
	if(QDir().exists(homePath + "/Eigene Dateien"))
		homePath += "/Eigene Dateien";
	else if(QDir().exists(homePath + "/My Documents"))
		homePath += "/My Documents";

	QString fileName = QFileDialog::getSaveFileName(m_view,
		tr("Export Trace"),
		homePath + "/Trace_" + QDate::currentDate().toString(Qt::ISODate),
		tr("CSV-File (*.csv)"));

	if(fileName.isNull())
		return;

	QFile f(fileName);

	if(!f.open(QIODevice::WriteOnly))
	{
		QMessageBox::critical(m_view,
			tr("Error"),
			tr("Could not open file."));
		return;
	}



	QString header = "Time; Class; Thread; Message\n";
	f.write(header.toLatin1());

	for(int i = 0; i < m_model->rowCount(); i++)
	{
		QString line = 	  m_model->data(m_model->index(i, 1), Qt::DisplayRole).toString() + ";"
						+ m_model->data(m_model->index(i, 2), Qt::DisplayRole).toString() + ";"
						+ m_model->data(m_model->index(i, 3), Qt::DisplayRole).toString() + ";"
						+ m_model->data(m_model->index(i, 4), Qt::DisplayRole).toString() + "\n";

		f.write(line.toLatin1());
	}

	f.close();

	QMessageBox::information(m_view,
		tr("Export"),
		tr("The trace was successfully exported."));

}


void QrfeTraceModel::setHeader()
{
	m_model->setHorizontalHeaderLabels(QStringList() << "Index" <<"Time" << "Class" << "Thread" << "Message");
}
