// amccmdserversocket.cpp: Implementierung der Klasse CoCoControler.
//
//////////////////////////////////////////////////////////////////////

#include "amccmdserversocket.h"
#include "activemirrorcontrol.h"
#include "cc_defs.h"

#include <qtimer.h>
#include <qsocket.h>
#include <qregexp.h>
#include <qtextstream.h>

#include <stdlib.h>

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

AMCCmdServerSocket::AMCCmdServerSocket( QObject* parent ) :
	QServerSocket( AMC_CMD_PORT, 0, parent)
{
	m_pParent = (ActiveMirrorControl*) parent;

	if ( !ok() ) {
	    qWarning( "Failed to bind to port %d", AMC_REP_PORT );
	    exit(1);
	}
}

AMCCmdServerSocket::~AMCCmdServerSocket()
{

}

void AMCCmdServerSocket::newConnection( int socket)
{
	QSocket* s = new QSocket(this);
	connect( s, SIGNAL( readyRead() ), SLOT(readClient()));
	connect( s, SIGNAL( connectionClosed() ), SLOT(discardClient()));
  connect( s, SIGNAL( error( int ) ), SLOT( error( int ) ) );
	s->setSocket(socket);

  connect( &m_qtTimer, SIGNAL( timeout( ) ), SLOT( timeout() ) );
	m_qtTimer.start( AMC_REPORT_TIMEOUT, true );

	emit newConnect();
}

void AMCCmdServerSocket::readClient()
{
//	qDebug( "msg from CC" );
	QSocket* socket = (QSocket*)sender();
	if (socket->canReadLine()) 
	{
		QString msg = socket->readLine();
		if( msg.startsWith("CC-REPORT") )
		{
			m_qtTimer.stop();
			m_qtTimer.start( CC_REPORT_TIMEOUT, true );
			qDebug( msg );
			emit reportFromCC( msg );
//			m_pParent->setAMCState( iStatus );
		}
		else
		{
			qDebug( msg );
			emit cmdFromCC( msg );
		}
	}		
}

void AMCCmdServerSocket::discardClient()
{
	QSocket* socket = (QSocket*)sender();
	delete socket;
	emit endConnect();
}

/** Slot called when a TCP error occures. */
void AMCCmdServerSocket::error( int p_iErrno )
{
	QString errText;
	switch( p_iErrno )
	{
	case QSocket::ErrConnectionRefused:
		errText.sprintf( "TCPIP error: ConnectionRefused" );
		break;
	case QSocket::ErrHostNotFound :
		errText.sprintf( "TCPIP error: HostNotFound " );
		break;
	case QSocket::ErrSocketRead :
		errText.sprintf( "TCPIP error: SocketRead " );
		break;
	default:
		errText.sprintf( "TCPIP error: Unknown" );
		break;
	}
	qDebug( errText );
	emit errorFromSocket( errText );
}


void AMCCmdServerSocket::timeout()
{
//	m_pParent->setAMCState( AMC_STATE_NOT_AVAILABLE );
}

