/*******************************************************************************
 * Copyright (c) 2005 Intel Corporation, IBM.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Vishnu K Naikawadi, Intel - Initial API and Implementation (Based on the Java
 *                                API implementation by IBM)
 *
 * $Id: ConsoleDataProcessor.cpp,v 1.11 2005/10/28 19:48:50 kcallaghan Exp $
 *
 *******************************************************************************/ 


#include "ConsoleDataProcessor.h"
#include "tptp/dime.h"
#include "tptp/NoLog.h"


ConsoleDataProcessor::ConsoleDataProcessor()
{
    tptp_initializeSemaphore(&hasProcessIdSemaphore);
}

ConsoleDataProcessor::~ConsoleDataProcessor()
{
    tptp_deleteSemaphore(&hasProcessIdSemaphore);
}


/**
 * Handle the data coming 
 */
void ConsoleDataProcessor::incomingData(char buffer[], int length, DIME_HEADER_PTR_T dimeHeader)
{
	
	long pid = get_dime_process_id(dimeHeader);

	//TPTP_STDOUT or TPTP_STDIN or TPTP_STDERR
	//TODO - Send STDOUT and STDIN messages to separate respective data processors 
	// currently all the messages go to the registered single data processor
	int consoleType = get_dime_console_type(dimeHeader);

	TPTP_LOG_DEBUG_MSG2("Incoming console data for PID %lu, console type: %d", pid, consoleType);

	IDataProcessor* dataProcessor = this->findDataProcessor(pid);

	do
	{
		dataProcessor = this->findDataProcessor(pid);

		if (dataProcessor == NULL)
		{
			TPTP_LOG_DEBUG_MSG1("Incoming console data: Waiting for data processor for PID %lu.", pid);
			tptp_waitSemaphore(&hasProcessIdSemaphore) ;
		}
	}
	while (dataProcessor == NULL) ;
	dataProcessor->incomingData(buffer, length, dimeHeader);
}


/**
 * Invalid Data Type
 */
void ConsoleDataProcessor::invalidDataType(char data[], int length)
{
	
}


/**
 * Waiting for data
 */
void ConsoleDataProcessor::waitingForData()
{
	
}



void ConsoleDataProcessor::addDataProcessor(long pid, IDataProcessor* dataProcessor)
{
	TPTP_LOG_DEBUG_MSG1("Add Console data processor for PID: %lu", pid);

	map<long, IDataProcessor*>::iterator  mapIterator = _contextMapper.find(pid);
	if ((mapIterator == _contextMapper.end()) && (dataProcessor != NULL))
	{
		_contextMapper.insert(map<long, IDataProcessor*>::value_type(pid, dataProcessor));

		tptp_postSemaphore(&hasProcessIdSemaphore) ;
	}
}


IDataProcessor* ConsoleDataProcessor::findDataProcessor(long pid)
{
	IDataProcessor* dataProcessor = 0;

	map<long, IDataProcessor*>::iterator  mapIterator = _contextMapper.find(pid);
	if (mapIterator != _contextMapper.end())
	{
		dataProcessor = (IDataProcessor*)mapIterator->second;
	}

	return dataProcessor;
}




