//
// 
//	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
// 
//	This program is free software; you can redistribute it 
//	and/or modify it under the terms of the GLOBALBASE 
//	Library General Public License (G-LGPL) as published by 
//
//	http://www.globalbase.org/
// 
//	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.
//
//

#include <LTextEditView.h>
#include <LWindow.h>
#include <mac_cosmos.h>

extern "C" {

typedef struct windowList {
	struct windowList * next;
	void * id;
	LWindow * win;
} windowList;

windowList * windowListHead = nil;
void insertLog(void * id, void * data, int len);


void newLogWindow(void * id);

void
newLogWindow(void * id)
{
unsigned char name[32];
LWindow * win;
windowList * list;

	for ( list = windowListHead ; list ; list = list->next )
		if ( list->id == id )
			break;
	if ( list ) {
		dynamic_cast<LTextEditView*>(list->win->FindPaneByID(2000))->Insert("*****\r",6);
		return;
	}
	win = LWindow::CreateWindow(200,theApp);
	sprintf((char*)name+1, "Log : %p", id);
	*name = strlen((char*)name+1);
	win->SetDescriptor(name);
	list = new windowList;
	list->next = windowListHead;
	list->id = id;
	list->win = win;
	windowListHead = list;
}

void
insertLog(void * id, void * data, int len)
{
windowList * list;
LTextEditView* tev;
unsigned char buf[10], c;
	for ( list = windowListHead ; list ; list = list->next )
		if ( list->id == id )
			break;
	if ( ! list )
		return;
	tev = dynamic_cast<LTextEditView*>(list->win->FindPaneByID(2000));
	for ( int i = 0 ; i < len ; i++ ) {
		c = *((char*)data+i);
		if ( c == '\n' )
			tev->Insert("\r",1);
		else if ( c == '\r' )
			tev->Insert("[CR]",4);
		else if ( c < 32 ) {
			sprintf((char*)buf,"[%02x]",c);
			tev->Insert(buf,4);
		} else 
			tev->Insert(&c,1);
	}
}

} // extern "C"