/*
Copyright (C) 2006 Evan Teran
                   eteran@alum.rit.edu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "DebugEventServer.h"
#include "Debugger.h"
#include "DebuggerCoreInterface.h"
#include <QtDebug>
#include <QEventLoop>
#include <QCoreApplication>

//------------------------------------------------------------------------------
// Name: DebugEventServer(QObject *parent)
// Desc: constructor
//------------------------------------------------------------------------------
DebugEventServer::DebugEventServer(QObject *parent) : QThread(parent), m_ShouldExit(false) {
}

//------------------------------------------------------------------------------
// Name: run()
// Desc: entry point of the event server's thread
// Note: would be nice if we could replace all this with SIGCHLD trapping, but
//       I've had difficulty with that so far
//------------------------------------------------------------------------------
void DebugEventServer::run() {
// on windows, we have timeouts so we integrate with the main event loop
#ifdef Q_OS_WIN32
	bool ok;
	DebugEvent e;
	edb::v1::debuggerBase->waitForDebugEvent(e, ok, 10);
	if(ok) {
		emit debugEvent(e);
	}
#else
	qDebug("Event Server Started");	
	m_ShouldExit = false;

	while(!m_ShouldExit) {

		DebugEvent event;
		bool ok;
		do {
			edb::v1::debuggerBase->waitForDebugEvent(event, ok, 10);
			if(m_ShouldExit) {
				break;
			}
			
		} while(!ok);
		
		if(!m_ShouldExit) {
			emit debugEvent(event);
		}
	}
	
	qDebug("Event Server Exited");
#endif
}
