#include "StdAfx.h"
#include "consolewindow.h"
#include <ATLComTime.h>

ConsoleWindow::ConsoleWindow(void)
{
	logfp = NULL;
}

ConsoleWindow::~ConsoleWindow(void)
{
}

int ConsoleWindow::Create(HWND parent)
{
	Load("console");
	title = env.GetWideString("console","title",L"BridgeConsole");
	titlebar.Load("console::titlebar");
	titlebar.title = title;
	if(SkinnableFrame::Create(parent)){
		padding = resize.size.Width;
		// the history window
		history.Load("console::history");
		history.scrollbar.Load("console::scrollbar");
		history.location = Point(padding,padding+titlebar.size.Height);
		history.size = Size(size.Width-padding*2,size.Height-padding*2-titlebar.size.Height);
		history.Create(hWnd,ES_LEFT|ES_MULTILINE|ES_AUTOVSCROLL|ES_READONLY);
		history.SetText(L"");
		return 1;
	} else
		return 0;
}

void ConsoleWindow::OnSize(int cx, int cy)
{
	SkinnableFrame::OnSize(cx,cy);
	history.SetSize(size.Width-2*padding,size.Height-2*padding-titlebar.size.Height);
}

#define ID_CONSOLEWINDOW_PUT 1212

void ConsoleWindow::Put(const TCHAR * format, ...)
{
	if(hWnd && history.hEditCtrl){
		TCHAR * buffer = new TCHAR[4096];
		va_list args;
		va_start(args, format);
		vswprintf(buffer,format,args);
		PostMessage(hWnd,ID_GENERIC,ID_CONSOLEWINDOW_PUT,(LPARAM)buffer);
		DoEvents();
	}
}

void ConsoleWindow::OnGeneric(WPARAM wParam, LPARAM lParam)
{
	if(wParam==ID_CONSOLEWINDOW_PUT){
		TCHAR * buffer = (TCHAR*)lParam;
		int nlines = SafeSendMessage(history.hEditCtrl,EM_GETLINECOUNT,0,0);
		if(nlines > 1000) // limit to 100 lines of text
			history.SetText(buffer);
		else
			history.AppendText(buffer);

		// optionally output to the log file
		if(logfp){
			COleDateTime now = COleDateTime::GetCurrentTime();
			_ftprintf(logfp,L"{%s}: %s",now.Format(L"%I:%M:%S %p"),buffer);
			fflush(logfp);
		}

		DoEvents();
		delete [] buffer;
	}
}

void ConsoleWindow::StartLogging(const TCHAR * filename)
{
	logfilename = filename;
	if(logfp)
		StopLogging();

	logfp = _tfopen(logfilename.data(),L"a+t");
	if(logfp==NULL){
		print(L"ConsoleWindow::StartLogging: Unable to open %s\n",logfilename.data());
	} else {
		COleDateTime now = COleDateTime::GetCurrentTime();
		print(L"--------------------- Logging to %s (%s)\n",logfilename.data(),now.Format(L"%c"));
	}
}

void ConsoleWindow::StopLogging()
{
	if(logfp){
		COleDateTime now = COleDateTime::GetCurrentTime();
		print(L"--------------------- Stopped logging (%s).\n",now.Format(L"%c"));
		fclose(logfp);
	}
	logfp = NULL;
}
