// LaserThread.cpp: Implementierung der Klasse LaserThread.
//
//////////////////////////////////////////////////////////////////////

#include "laserthread.h"
#include "motorthreaddialog.h"
#include "threadevent.h"
#include "amcmirrorpanel.h"
#include "amcmotor.h"
#include "amcserialport.h"
#include "amcerror.h"
#include <qmessagebox.h>
#include <qevent.h>
#include <qthread.h>
#include <qstring.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

extern AMCSerialPort* g_pPort[];

//////////////////////////////////////////////////////////////////////
// Konstruktion/Destruktion
//////////////////////////////////////////////////////////////////////

LaserThread::LaserThread( QObject* p_pReceiver )
	: m_pPanel( NULL ), m_pReceiver( p_pReceiver ), m_zOn( false )
{
}

LaserThread::~LaserThread()
{
}

void LaserThread::run()
{
	QString qsMsg;
	qsMsg.sprintf( "Panel (%d,%d)  Port: %d, Box:%d, Driver:%d",
			       m_pPanel->i(), m_pPanel->j(), m_pPanel->port(), m_pPanel->box(), m_pPanel->driver() );
	QThread::postEvent( m_pReceiver, new ThreadEvent( qsMsg ) );

	QTime t;
	t.start();                          // start clock

	
	// We use only one motor instance and reuse it for each panel
	AMCSerialPort* pPort = g_pPort[ m_pPanel->port()-1 ];
	AMCMotor* pMotor = new AMCMotor( pPort );

	try
	{
		msleep(30);
		pMotor->unselectBox();
		pMotor->selectBox( m_pPanel->box() );
		pMotor->selectDriver( m_pPanel->driver() );
		msleep(10);
		pMotor->switchLaser( m_zOn );
		m_pPanel->setLaserOn( m_zOn );		
	}
	catch( AMCError& e )
	{
		qsMsg.sprintf( "AMCError: Panel (%d,%d)  Port: %d, Box:%d, Driver:%d -- ",
			       				m_pPanel->i(), m_pPanel->j(), m_pPanel->port(), m_pPanel->box(), m_pPanel->driver() );
		qsMsg.append( e.getErrorText() );
		QThread::postEvent( m_pReceiver, new ThreadErrorEvent( qsMsg, e ) );
		pMotor->resetBox();
	}
	delete pMotor;

	qsMsg.sprintf( "Time: %dms", t.elapsed() );
	QThread::postEvent( m_pReceiver, new ThreadEvent( qsMsg ) );
	QThread::postEvent( m_pReceiver, new QCustomEvent( PROGRESS_EVENT ) );

}

void LaserThread::setPanel(AMCMirrorPanel* p_pPanel)
{
	m_pPanel = p_pPanel;
}

