#include "sock.h"
#include "clientthread.h"
#include "bstream.h"
#include "config.h"
#include "client.h"
#include "notifyicon.h"
#include <process.h>

class CClientThread::CClientListener : public IClientListener
{
public:
	CClientListener( CNotifyIcon * pIcon ) : m_pIcon(pIcon) {}
	void Notification( const std::string& title, const std::string& message )
	{
		m_pIcon->SetNotification( title, message );
	}
	void Tip( const std::string& msg )
	{
		m_pIcon->SetTip( msg );
	}
	void OnQuit() {}

private:
	CNotifyIcon * m_pIcon;
};

CClientThread::CClientThread( CNotifyIcon * pIcon )
{
	this->handle = (HANDLE) _beginthread( ClientUIThread, 0, pIcon );
	if (handle == INVALID_HANDLE_VALUE)
		throw CWinException();
}

CClientThread::~CClientThread()
{
	while (true)
	{
		try
		{
			CSock sock;
			sock.Bind(0);
			BOutputStream out;
			out << 'Q' << PROTOCOL_VERSION;
			sock.Send( 0x7f000001, CLIENT_PORT, out.GetPtr(), out.GetSize() );
			if (WAIT_OBJECT_0 == WaitForSingleObject( handle, 500 ))
				break;
		}
		catch (...)
		{
			if (WAIT_TIMEOUT == WaitForSingleObject( handle, 10000 ))
				MessageBox( GetDesktopWindow(), "Unable to exit correctly... may crash now", "Warning", MB_OK );
			break;
		}
	}
}

void CClientThread::ClientUIThread( void * ptr )
{
	// be nicer than our anti-virus software
	SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL );

	CClientListener listener( (CNotifyIcon *)ptr );
	DoClient( &listener );
}
