#include "__PLUGIN_NAME__SourcePlugin.h"
#include <QTimer>

__PLUGIN_NAME__SourcePlugin::__PLUGIN_NAME__SourcePlugin()
{
	// Create source
	m_Source = __PLUGIN_NAME__SourcePluginSourceType::New();

	// Initialize timer
	m_Timer = new QTimer();		
	m_Timer->stop();
	connect(m_Timer, SIGNAL(timeout()), this, SLOT(RequestFrame()));
 
	// Create GUI and connect player related buttons
	m_Widget = new __PLUGIN_NAME__SourcePluginWidget();
	
	// Connect elements from the widget
	connect(m_Widget->m_PushButtonPause,		SIGNAL(clicked()),	this,	SLOT(Pause())			);
	connect(m_Widget->m_PushButtonPlayForward,	SIGNAL(clicked()),	this,	SLOT(Play())			);
	connect(m_Widget->m_PushButtonStepForward,	SIGNAL(clicked()),	this,	SLOT(RequestFrame())	);

	// Connect the UpdateGUI mechanism
	connect(this, SIGNAL(UpdateGUI()), m_Widget, SLOT(UpdateGUI()));
}


__PLUGIN_NAME__SourcePlugin::~__PLUGIN_NAME__SourcePlugin()
{
	// Clean up widget (this is mandatory!)
	if ( m_Widget )
		delete m_Widget;

	// Delete timer
	if ( m_Timer )
		delete m_Timer;
}


//----------------------------------------------------------------------------
QWidget*
__PLUGIN_NAME__SourcePlugin::GetPluginGUI()
{
	return m_Widget;
}


//----------------------------------------------------------------------------
__PLUGIN_NAME__SourcePlugin::SourcePlugin::SourcePointer 
__PLUGIN_NAME__SourcePlugin::GetSource()
{	
	return (SourcePlugin::SourceType*)m_Source;
}


//----------------------------------------------------------------------------
void
__PLUGIN_NAME__SourcePlugin::SetState(StateType State)
{
	// Lock
	{
		QMutexLocker locker(&m_StateMutex);
		m_State = State;

		// Update widget
		if ( m_Widget )
		{
			switch ( m_State )
			{
			case Idle:
				m_Widget->m_PushButtonPause->setEnabled(false);
				m_Widget->m_PushButtonPlayForward->setEnabled(true);
				m_Widget->m_PushButtonStepForward->setEnabled(true);
				break;
			case Playing:
				m_Widget->m_PushButtonPause->setEnabled(true);
				m_Widget->m_PushButtonPlayForward->setEnabled(false);
				m_Widget->m_PushButtonStepForward->setEnabled(false);
				break;
			}
			emit UpdateGUI();
		}
	}
}


//----------------------------------------------------------------------------
void
__PLUGIN_NAME__SourcePlugin::Play()
{
	SetState(Playing);
	m_Timer->start(20);
}


//----------------------------------------------------------------------------
void
__PLUGIN_NAME__SourcePlugin::Pause()
{
	m_Timer->stop();
	SetState(Idle);
}


//----------------------------------------------------------------------------
void
__PLUGIN_NAME__SourcePlugin::RequestFrame()
{
	// ======================= //
	// Update your source here //
	// ======================= //
	// ...

	m_AcquisitionPipeline->Lock();

	// We need to modify the source
	m_Source->Modified();

	m_AcquisitionPipeline->Unlock();

	// Trigger pipeline execution
	m_AcquisitionPipeline->ExecuteOnce();
}