// centerthread.cpp: Implementierung der Klasse CenterThread.
//
//////////////////////////////////////////////////////////////////////

#include "centerthread.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>

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

extern AMCSerialPort* g_pPort[];

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

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

CenterThread::~CenterThread()
{
}

void CenterThread::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 ) );

	// 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
	{
		pMotor->unselectBox();
		pMotor->selectBox( m_pPanel->box() );
		pMotor->selectDriver( m_pPanel->driver() );
		pMotor->getFrequency();

		pMotor->centerMotors();
		pMotor->waitForMotors( pMotor->calcTimeout( 17000 )+2 );
		m_pPanel->setX( 0 );
		m_pPanel->setY( 0 );
	}
	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() );
		qDebug("Posted error event");
		QThread::postEvent( m_pReceiver, new ThreadErrorEvent( qsMsg, e ) );
		pMotor->resetBox();
	}

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

}

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