#include <ctype.h>
#include <string.h>
#include <stream.h>
#include "cgidbg.h"
#include "shared.h"
#include "remcom.h"
#include "call_back.h"
#include "mpacket.h"
#include "menu.h"
#include "dsp_app.h"
#include "xdrv.h"
#include "xgui.h"
#include "dsp_app.h"


InputCallback::InputCallback(InputType t):
	type(t)
{}

static char * remove_blanks(const char * x)
{
	if (!x) return 0 ;
	while(*x && isspace(*x)) x++;
	const char * last = x + strlen(x) - 1 ;
	if (last < x) return 0 ;
	while (isspace(*last) && last >= x) last-- ;
	if (last < x) return 0 ;
	char * ret = new char [last - x + 2] ;
	char * dest = ret ;
	for (const char * t = x ; t <= last; t++) *dest++ = *t ;
	*dest = '\0' ;
	return ret ;
}

void InputCallback::record(const char * str)
{
	switch(type) {
		default:
		case InputPrompt:
		case InputPlot:
		case InputAcknowledge:
		case InputNotInitialized:
		case InputUndefined:
		case InputEndOfInputTypes:
		case InputHelp:
			DbgError("InputCallback::record","bad type");
			break ;
		case InputCppEntry: 
			DspApplication::record_dpp_text(str);
			break ;
		case InputMenu:
			DspApplication::record_menu_text(str);
			break ;
	}
}

void InputCallback::WriteLine(const char *str, TxtWindow * win)
{
	// LogOut << "InputCallback::WriteLine(" << str << ",)\n" ;
	char * temp = remove_blanks(str);
	const limit = 120 ;
	if (strlen(temp) > limit) {
		temp[limit] = '\0' ;
		// LogOut << "truncating `" << str << "\nto " << temp << "\n" ;
		*Output + OutputCppHelp <<
			"Warning: input string truncated to " << limit << " characters.\n" ;
	}
	if (!temp) return ;
	switch(type) {
		case InputNotInitialized:
		case InputUndefined:
		case InputEndOfInputTypes:
		case InputHelp:
			DbgError("InputCallback::WriteLine","bad type");
		case InputPrompt:
		case InputPlot:
		case InputAcknowledge:
			cerr << "InputCallback::WriteLine(\"" << str << "\"), type = " <<
				type << " not implemented.\n" ;
			break ;
		case InputCppEntry: {
			DspApplication::state()->write_cpp_line(temp) ;
			break ;
		}
		case InputMenu:
			DspApplication::root_window()->do_command(temp);
	}
	delete temp ;
}
