/*
 * (c) 2005 Research Group Dr. Fuhrmann, University of Karlsruhe, Germany
 * All rights reserved.
 *
 * Author:
 *         Stefan Denk <denk@ira.uka.de>
 *         Kendy Kutzner <kutzner@ira.uka.de>
 *
 * $Id: vtmsg.cc,v 1.4 2006/01/05 10:31:44 denk Exp $
 *
 */

// stdlib

#include <sstream>
using namespace std;

// libc
#include <assert.h>

// vidtrans

#include "vtmsg.h"

string vtmsg::tostring(){
	stringstream s;
	switch (type){
		case DATA:
			s << "DATA";
			break;
		case REQ:
			s << "REQ";
			break;
		default:
			assert(0);
	}
	s << endl;
	s << dest.tostring();
	s << endl;
	for (sourcelist_t::const_iterator i = sources.begin(); i!= sources.end(); i++){
		s << (*i)->tostring();
		s << endl;
	}
	return s.str();
}

/**
 * This function transforms something we got from the igor into
 * an internal message.
 * \param buf pointer to message. Not modified.
 * \param len len of message.
 * \return true if parsing was successful.
 */
bool
vtmsg::fromstring(const char *buf , int len){
	//dsyslog("%s: parsing message of len %i", __PRETTY_FUNCTION__, len);
	string s;
	s.append(buf, len);
	stringstream ss(s);
	string line;
	
	getline(ss, s);
	//printf("start parsing vtmsg: %s\n", s.substr(0,80).c_str());
	if (s == "DATA"){
		type = DATA;
	} else if (s == "REQ") {
		type = REQ;
	} else {
		return false;
	}
	//dsyslog("%s: msgtype %i", __PRETTY_FUNCTION__, type);
	getline(ss, s);
	if (! dest.fromstring(&s))
		return false;
	// printf("dest %s parsed: %s\n", s.substr(0,50).c_str(), dest.tostring().c_str());
	//dsyslog("%s: dest %s parsed: %s", __PRETTY_FUNCTION__, s.c_str(), dest.tostring().c_str());
	bool found = false;
	// request messages do not need sources.
	if ( type == REQ ) found = true;
	while (true){
		cvideosource vs;
		getline(ss, s);
		//printf("parsing videosource: %s\n", s.substr(0,80).c_str());
		if (!vs.fromstring(&s))
		{
			if (found)
			{
				//printf("parsing vtmsg finished with success\n");
				return true;
			}
			else
			{
				//printf("parsing vtmsg finished with failure\n");
				return false;
			}
		}
		cvideosource * vsp = new cvideosource(vs);
		sources.push_back(vsp);
		//dsyslog("%s: source parsed", __PRETTY_FUNCTION__);
		found = true;
	}
	// never reached
	assert(0);
	return true;
}

