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

#include <string.h>
#include <winsock.h>
#include "Telnet.h"
#include "Resource.h"
#include "TelnetApp.h"
#include "TelnetEngine.h"
#include "EmulatorEngine.h"
//#include "TerminalEngine.h"
#include "TelnetSession.h"
#include "WinSizeOption.h"
#include "EncryptOption.h"

TelnetSession::TelnetSession(void)
{
}

BOOL TelnetSession::Connect(char *hostname)
{
	mTelnetEngine	=		new TelnetEngine(this);
	mTerminalEngine	=		new EmulatorEngine(this);
//	mCryptoEngine	=		new CryptoEngine(&mTelnetEngine->enckey);

	mTerminalEngine->Open();
	mTelnetEngine->Connect(hostname);
	return TRUE;
}

void TelnetSession::RecCallback(CharStream *RecStream)
{
	unsigned char c, *buf;
	unsigned int bufSZ;
	
	while(RecStream->GetChar(&c))
	{
		RecStream->UngetChar();
		if(c == IAC)
		{
			mTelnetEngine->TelnetNegotiate(RecStream);
		}
		else
		{
			 mTerminalEngine->ReceivedFromHost(RecStream);
		}

	
		/*RecStream->UngetChar();
		if(RecStream->SkipTo(IAC, &buf, &bufSZ))
		{
			if(bufSZ > 0)
				mTerminalEngine->ReceiveBuffer(buf,bufSZ);
			mTelnetEngine->TelnetNegotiate(RecStream);
		}
		else
		{
			if(bufSZ == 0)
				return;
			mTerminalEngine->ReceiveBuffer(buf,bufSZ);
		}
		
		// Free memory allocated by SkipTo.
		if(buf) delete []buf;
		*/
	}
}

void TelnetSession::ConnectionBroken(void)
{
	unsigned char msg[] = "Connection closed by remote host.\n";
	mTerminalEngine->ReceiveBuffer(msg, sizeof(msg));
	Close();
}

void TelnetSession::Close(void)
{
	mTelnetEngine->Close();
	mTerminalEngine->Close();
	theApp->SessionClosed(this);
}

void TelnetSession::InvokeCommand(unsigned short command, void* Data)
{
	char *msg_text;
	switch(command)
	{
	// Connection menu items.	
	case ID_CONNECTION_CLOSE:
		Close();
		break;

	// Telnet menu items
	case ID_TELNET_SEND_AYT:
		mTelnetEngine->SendCommand(AYT);
		break;
	
	case ID_TELNET_SEND_BRK:
		mTelnetEngine->SendCommand(BRK);
		break;
	
	case ID_TELNET_SEND_IP:
		mTelnetEngine->SendCommand(IP);
		break;
	
	case ID_TELNET_SEND_AO:
		mTelnetEngine->SendCommand(AO);
		break;
	
	case ID_TELNET_SEND_EC:
		mTelnetEngine->SendCommand(EC);
		break;

	case ID_TELNET_SEND_EL:
		mTelnetEngine->SendCommand(EL);
		break;

	// Encryption menu items.
	case ID_ENCRYPTION_ON:
		mTelnetEngine->InvokeOption(ENCRYPT_OPT, ENCRYPT_ON);
		break;

	case ID_ENCRYPTION_OFF:
		mTelnetEngine->InvokeOption(ENCRYPT_OPT, ENCRYPT_OFF);
		break;

	// About menu items.
	case ID_SHOWVERSION:
		msg_text = "NADA Telnet: Version 1.0 BETA\nAuthor: J Karlsson <d93-jka@nada.kth.se>\nCopyright 1996 NADA, KTH\nPlease send bugreports to d93-jka@nada.kth.se";
		MessageBox(mTerminalEngine->mWindow, msg_text,
				"NADA Telnet", MB_OK|MB_ICONINFORMATION);
		break;
		
	// Window size changed.
	case WINSIZE_CHANGED:
		mTelnetEngine->InvokeOption(NAWS, WINSIZE_CHANGED, Data);
		break;
	}
}

