/**@file string_behaviors.cc
 *
 * Implements string_behaviors.hh
 *
 */


#include "string_behaviors.hh"

using namespace std;

/**
 * BufferString Behavior
 */

BufferString::BufferString()
{
}


int BufferString::Execute()
{
	CharLink *l = reinterpret_cast<CharLink*>(FindMaxNonGenericInputSignal());
	
	if(l)
	{
		char c = l->Char();
	
		switch(c)
		{
		case(' '):
			out_s = in_s;							// copy string to out
			in_s.erase(in_s.begin(),in_s.end());	// erase in string
			return 1;
			break;

		case((char)13):
			out_s = in_s;							// copy string to out
			out_s+=c;								// add trailing carriage return
			in_s.erase(in_s.begin(),in_s.end());	// erase in string
			return 1;
			break;
			
		default:
			in_s+=c;	// concatenate character on string
			return 0;
		}
	}

	return 0;
}


void BufferString::Feed(SignalLink &l)
{
	if (!l.Generic())
		reinterpret_cast<StringLink&>(l).String(out_s);

	Behavior::Feed(l);
}


BufferString& operator>>(CharLink& l, BufferString& o)
{
	SignalLinkOutputToBehavior(l,o);
	return o;
}


StringLink& operator>>(BufferString& n, StringLink& o)
{
	BehaviorOutputToSignalLink(n,o);
	return o;
}




/**
 * BufferSentence Behavior
 */

BufferSentence::BufferSentence()
{
}


int BufferSentence::Execute()
{
	StringLink *l = reinterpret_cast<StringLink*>(FindMaxNonGenericInputSignal());

	if(l)
	{
		string s = l->String();		// get a copy of the string
		char c = s[s.length()-1];	// get the last character

		in_s+=s;	// concatenate string on sentence

		switch(c)
		{
		case((char)13):								// Enter was pressed
			out_s = in_s;							// copy string to out
			in_s.erase(in_s.begin(),in_s.end());	// erase in string
			return 1;
			break;
		
		default:
			in_s+=' ';  // add an extra space
			return 0;
		}
	}

	return 0;	
}


void BufferSentence::Feed(SignalLink &l)
{
	if (!l.Generic())
		reinterpret_cast<StringLink&>(l).String(out_s);

	Behavior::Feed(l);
}


BufferSentence& operator>>(StringLink& l, BufferSentence& o)
{
	SignalLinkOutputToBehavior(l,o);
	return o;
}


StringLink& operator>>(BufferSentence& n, StringLink& o)
{
	BehaviorOutputToSignalLink(n,o);
	return o;
}







