// TelnetApp.cpp
// Author: Jörgen Karlsson - d93-jka@nada.kth.se

#include <Windows.h>
#include <winsock.h>
#include "TelnetApp.h"
#include "TelnetEngine.h"
#include "TerminalEngine.h"
#include "TelnetSession.h"
#include "Resource.h"

TelnetApp *theApp;
TelnetSession *theSession;
HANDLE theEvent[1];
int EventCount;

const int hostnameSZ = 64;
char hostname[hostnameSZ] = "";

BOOL CALLBACK host_dialog_proc(HWND  hwndDlg, UINT  uMsg, WPARAM  wParam, LPARAM  lParam)
{
	switch(uMsg)
	{
		case WM_INITDIALOG:
 			SetDlgItemText(hwndDlg, IDC_EDIT1, hostname);
			return TRUE;
			break;
		case WM_COMMAND: 
			switch(wParam)
			{
				case IDOK:
					if(!GetDlgItemText(hwndDlg,IDC_EDIT1, hostname ,hostnameSZ))
						EndDialog(hwndDlg, IDCANCEL);
				case IDCANCEL:
					EndDialog(hwndDlg, wParam);
				return TRUE;
				break;
			}
	}
	return FALSE;
}


int WINAPI WinMain(HINSTANCE  hInst, HINSTANCE  hPrevInst,
				   LPSTR  CmdLine, int  nShowCmd)
{
	MSG  msg;
	TelnetApp app(hInst);
	while(TRUE)
	{
	GetMessage(&msg, 0,0,0);
	{
		switch(msg.message)
		{
		case WM_QUIT:
			return msg.wParam;

		case WM_ENDSESSION:
			theApp->CloseAllSessions();
			return 0;
			break;

		default:
			TranslateMessage(&msg); 
			DispatchMessage(&msg);
		}
	}
	}
}


TelnetApp::TelnetApp(HINSTANCE hInst)
{
	WORD version;	
	WSADATA data; 
	TelnetSession *session;
	char *hostname;

	AppInstance = hInst; 
	theApp = this;
	version = MAKEWORD(1, 1); 
	if(WSAStartup(version, &data) != 0)
		exit(1);

	if(hostname = GetHostName(""))
	{
		session = new TelnetSession();
		if(session->Connect(hostname))
			theSession = session;		
	}
	else
		SessionClosed(0);
}	
	
TelnetApp::~TelnetApp(void)
{
	if(WSACleanup() == SOCKET_ERROR)
		exit(1);
}

void TelnetApp::Error(int ErrorCode, char *ErrorString)
{
	OutputDebugString("TelnetApp::Error.\n");
	if(ErrorString)
		OutputDebugString(ErrorString);
	exit(ErrorCode);
}

void TelnetApp::SessionClosed(TelnetSession *thisTelnetSession)
{
	PostQuitMessage(0);
}

char* TelnetApp::GetHostName(char* defaultHost)
{
	PHOSTENT host;
	strcpy(hostname, defaultHost);
askforhost:
	HWND wnd = GetActiveWindow();
	HANDLE hInst = theApp->AppInstance;
	switch(DialogBox(hInst,MAKEINTRESOURCE(IDD_DIALOG1),wnd,(DLGPROC)host_dialog_proc))
	{
	case IDOK:
		if(!(host = gethostbyname(hostname)))
		{
			TelnetApp::Message("Unknown host.");
			goto askforhost;
		}
		return host->h_name;
	case IDCANCEL:
	default:
		return NULL;
	}
}


void TelnetApp::RegisterRecEvent(HANDLE RecEvent)
{
	theEvent[0] = RecEvent;
	EventCount = 1;
	
}

void TelnetApp::CloseAllSessions(void)
{
	theSession->Close();
}

void TelnetApp::Message(char *text)
{
	HWND wnd = GetActiveWindow();
	MessageBox(wnd, text, "NADA Telnet message", MB_ICONERROR|MB_OK|MB_APPLMODAL);
}
