#include "motorthreaddialog.h"
#include "amclog.h"
#include "amcmirrorpanel.h"
#include "magicmirror.h"	
#include "motorthread.h"
#include "motorthreadcontroller.h"
#include "laserthread.h"
#include "laserthreadcontroller.h"
#include "threadevent.h"
#include <stdlib.h>
#include <time.h>
#include <qpushbutton.h>
#include <qprogressbar.h>
#include <qdatetime.h>
#include <qthread.h>
#include <qmultilineedit.h>
#include <qapplication.h>

extern AMCLog* g_pLog;
extern MagicMirror* g_theMirror;

MotorThreadDialog::MotorThreadDialog( QWidget* parent, const char* name, bool modal, WFlags f )
	: MotorThreadDlgBase( parent, name, modal, f )
{
	// Add your code
	m_zOn = false;
	ProgressBar1->setTotalSteps( g_theMirror->getNumPanels()-1 );
	m_pThreadSemaphore = new QSemaphore( 1 );
}

MotorThreadDialog::~MotorThreadDialog()
{
	delete m_pThreadSemaphore;
}

void MotorThreadDialog::startThread()
{
	ProgressBar1->reset();
	(*m_pThreadSemaphore)++;
	this->start();

	return;
}

void MotorThreadDialog::outputMessage(QString p_qsMsg)
{
	InfoField->append( p_qsMsg );
	InfoField->setCursorPosition( InfoField->numLines()+1, 0 );
}

void MotorThreadDialog::run()
{
	buttonApply->setEnabled( false );
  QTime t;
  t.start();                          // start clock

	MotorThreadController* pTController[8];
	for(int i=0; i<8; i++)
	{
		pTController[i] = new MotorThreadController( g_theMirror->panelForPort(i), this );
		pTController[i]->start();
	}

	for(int i=0; i<8; i++) {
		pTController[i]->wait();
		delete pTController[i];
	}

	QString qsMsg;
	qsMsg.sprintf( "Total Time: %dms", t.elapsed() );
	QThread::postEvent( this, new ThreadEvent( qsMsg ) );

	buttonApply->setEnabled( true );
	(*m_pThreadSemaphore)--;

}

void MotorThreadDialog::customEvent(QCustomEvent *e)
{
  if ( e->type() == THREAD_EVENT )
	{
		ThreadEvent* te = (ThreadEvent*)e;
		outputMessage( te->getMessage() );

	}
  if ( e->type() == THREAD_ERROR_EVENT )
	{
		ThreadErrorEvent* tee = (ThreadErrorEvent*)e;
		outputMessage( tee->getMessage() );
		g_pLog->logError( tee->getMessage(), tee->getError() );
	}
  if ( e->type() == PROGRESS_EVENT )
		ProgressBar1->setProgress( ProgressBar1->progress()+1 );

}
