/*
 * DemoController.cpp
 *
 *  Created on: 08.03.2011
 *      Author: stefan.detter
 */

#include "ToolController.h"

#include <def.h>
#include <QMessageBox>

#include "../permission/Permissions.h"

#include "../control/ReaderControll.h"

#include "Tool.h"

ToolController::ToolController(ModelData* root, ReaderControll* readerControl, QWidget* parentWidget, QObject* parent)
	: QObject(parent)
	, QrfeTraceModule("DemoController")
	, m_modelData(root)
	, m_readerControl(readerControl)
	, m_parentWidget(parentWidget)
{

}

ToolController::~ToolController()
{
}

QList<QString> ToolController::availableTools()
{
	return m_tools.keys();
}

QList<QString> ToolController::availableCustomTools()
{
	return m_customTools.keys();
}

QList<QString> ToolController::availableDemos()
{
	return m_demos.keys();
}


QList<QAction*> ToolController::getToolActions ( )
{
	return m_toolActions;
}

QList<QAction*> ToolController::getCustomToolsActions ( )
{
	return m_customToolsActions;
}

QList<QAction*> ToolController::getDemoActions ( )
{
	return m_demoActions;
}


void ToolController::permissionsChanged()
{
	bool successCustom = false;
	bool successDemo = false;
	Tool* tool = 0;

	if(successCustom)
		emit customToolsChanged();

	if(successDemo)
		emit demosChanged();
}

void ToolController::toolSelected()
{
	QAction* action = qobject_cast<QAction*>(sender());
	if(action == 0){
		trc(0, "Unknown sender...");
		return;
	}

	if(m_readerControl->inventoryActive())
	{
		QMessageBox::critical(m_parentWidget, "Reader Settings", "You must stop the scan before you can start a demo.");
		return;
	}

	QString name = action->data().toString();
	trc(0, "Starting tool >>" + name + "<<.");

	Tool* tool = 0;
	if(m_tools.keys().contains(name))
	{
		tool = m_tools.value(name);
	}
	else if(m_customTools.keys().contains(name))
	{
		tool = m_customTools.value(name);
	}
	else if(m_demos.keys().contains(name))
	{
		tool = m_demos.value(name);
	}
	if(tool == 0)
		return;

	tool->execTool();
}

bool ToolController::executeTool(QString name)
{
	if( !m_tools.contains(name) && !m_demos.contains(name) && !m_customTools.contains(name))
		return false;

	Tool* tool = 0;
	if(m_tools.keys().contains(name))
	{
		tool = m_tools.value(name);
	}
	else if(m_demos.keys().contains(name))
	{
		tool = m_demos.value(name);
	}
	else if(m_customTools.keys().contains(name))
	{
		tool = m_customTools.value(name);
	}

	if(tool == 0)
		return false;

	return tool->execTool();
}




QAction* ToolController::createAction ( Tool* t )
{
	QAction* a = new QAction(QIcon(t->icon()), t->name(), m_parentWidget);
	a->setData(t->name());
	connect(a, 		SIGNAL(triggered(bool)),
			this, 	  SLOT(toolSelected()));

	return a;
}



