/*
 * InformationTableController.cpp
 *
 *  Created on: 28.10.2009
 *      Author: stefan.detter
 */

#include "InformationTableController.h"

#include "InformationTableModel.h"

#include "../../application/Reader.h"

#include "../data/TreeItem.h"
#include "../data/ReaderEntry.h"
#include "../data/TagEntry.h"

#include "../treeModel/TagTreeControl.h"

#include <QHeaderView>


InformationTableController::InformationTableController(TagTreeControl* ttc, QTableView* tableView, QPushButton* advancedButton, QObject* parent)
	: QObject(parent)
	, m_tableView(tableView)
	, m_advancedButton(advancedButton)
	, m_ttc(ttc)
{
	m_informationTableModel = new InformationTableModel(this);

 	m_tableView->setModel(m_informationTableModel);

	m_tableView->setColumnWidth(0, 100);
	m_tableView->setColumnWidth(1, 100);

#if QT_VERSION > 0x050000
	m_tableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
	m_tableView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
#endif

	connect(m_advancedButton, SIGNAL(clicked()), this, SLOT(advancedButtonClicked()));

	connect(m_ttc, SIGNAL(itemClicked(const TreeItem*)), m_informationTableModel, SLOT(setInformationItem(const TreeItem*)) );
	connect(m_ttc, SIGNAL(itemClicked(const TreeItem*)), this, SLOT(setInformationItem(const TreeItem*)) );

	m_informationTableModel->setInformationItem(m_ttc->selectedItem());
	this->setInformationItem(m_ttc->selectedItem());
}

InformationTableController::~InformationTableController()
{
}

void InformationTableController::setInformationItem(const TreeItem* t)
{
	if(t == 0)
		return;

	m_advancedButton->setEnabled(true);

	switch(t->itemType())
	{
	case TreeItem::ROOT:
		m_advancedButton->setText("Application Settings");
		break;
	case TreeItem::READER:
	{
		m_advancedButton->setText("Reader Settings");

		const ReaderEntry* r = dynamic_cast<const ReaderEntry*>(t);
		if(r == 0)
			return;
		if( (r->reader()->readerCaps() & QrfeGlobal::READER_SETTINGS) == 0)
			m_advancedButton->setEnabled(false);
		break;
	}
	case TreeItem::TAG:
	default:
		m_advancedButton->setText("Tag Settings");
		break;
	}

	m_tableView->clearSpans();
	foreach(int row, t->informationSpan())
	{
		m_tableView->setSpan(row, 0, 1, 2);
	}
}

void InformationTableController::advancedButtonClicked()
{
	TreeItem* t = m_ttc->selectedItem();

	QList<QVariant> params;
	switch(t->itemType())
	{
		case TreeItem::ROOT:
		{
			emit appendGlobalJob(JOB_ShowApplicationSettings, params);
			break;
		}
		case TreeItem::READER:
		{
			ReaderEntry* r = (ReaderEntry*) t;
			params.append(r->readerId());
			emit appendGlobalJob(JOB_ShowSettingsOfReader, params);
			break;
		}

		case TreeItem::TAG:
		{
			TagEntry* tag = (TagEntry*) t;
			ReaderEntry* r = (ReaderEntry*) tag->parent();

			params.append(r->readerId());
			params.append(tag->tagId());
			params.append(tag->antennaId());

			emit appendGlobalJob(JOB_ShowSettingsOfTag, params);

			break;
		}
		default:
			break;
	}

}

