// movethread.cpp: Implementierung der Klasse MoveThread.
//
//////////////////////////////////////////////////////////////////////

#include "movethread.h"
#include "threadevent.h"
#include "amcmirrorpanel.h"
#include "amcmotor.h"
#include "amcserialport.h"
#include "amcerror.h"
#include <qevent.h>
#include <qthread.h>
#include <qstring.h>
#include "stdlib.h"

#define MAX(a,b) ((a>b) ? a : b )

extern AMCSerialPort* g_pPort[];

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

MoveThread::MoveThread( QObject* p_pReceiver )
	: m_pPanel( NULL ), m_pReceiver( p_pReceiver )
{
}

MoveThread::~MoveThread()
{
}

void MoveThread::run()
{
	QString qsMsg;

	// 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 );

	bool zLaser = false;
	try
	{
		pMotor->unselectBox();
		pMotor->selectBox( m_pPanel->box() );
		pMotor->selectDriver( m_pPanel->driver() );
		pMotor->getFrequency();

		int x = m_pPanel->getRefX();
		int y = m_pPanel->getRefY();
		int steps = MAX( abs(x), abs(y) );
		if( ! ((x == 0) && (y == 0)) )			// only move is necesary
		{
			pMotor->moveMotors(x,y);
			pMotor->waitForMotors( pMotor->calcTimeout(steps) );
		}
	}
	catch( AMCError& e )
	{
		qsMsg.sprintf( "AMCError: Port: %d, Box:%d, Driver:%d -- ",
			       				m_pPanel->port(), m_pPanel->box(), m_pPanel->driver() );
		qsMsg.append( e.getErrorText() );
		QThread::postEvent( m_pReceiver, new ThreadErrorEvent( qsMsg, e ) );
	}
	delete pMotor;

	QThread::postEvent( m_pReceiver, new QCustomEvent( THREAD_END_EVENT ) );

}

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