#include "clientui.h"
#include "winexcept.h"
#include "notifyicon.h"

struct AutoCloseWindow
{
	AutoCloseWindow( HWND hwnd ) { this->hwnd = hwnd; }
	~AutoCloseWindow() { CloseWindow(hwnd); }
	HWND hwnd;
};

static LRESULT WINAPI WndProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
	if (CNotifyIcon * pIcon = CNotifyIcon::Get())
	{
		switch (msg)
		{
		case WM_COMMAND:
			pIcon->OnCommand( LOWORD(wparam) );
			break;

		case msgUpdateNotification:
			pIcon->OnUpdateNotification();
			break;

		case msgUpdateTip:
			pIcon->OnUpdateTip();

		case msgIcon:
			if (wparam == uidIcon)
			{
				switch (lparam)
				{
				case WM_CONTEXTMENU:
					pIcon->OnContextMenu();
					break;
				case WM_RBUTTONDOWN:
					pIcon->OnRButtonDown();
					break;
				}
			}
			break;
		}
	}

	switch (msg)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}

	return DefWindowProc( hwnd, msg, wparam, lparam );
}

void DoClientUI()
{
	WNDCLASS cls;
	memset(&cls, 0, sizeof(cls));
	cls.lpfnWndProc = WndProc;
	cls.hInstance = GetModuleHandle(NULL);
	cls.lpszClassName = "BLOW";
	if (!RegisterClass( &cls ))
		throw CWinException();

	HWND hwnd = CreateWindow(
		"BLOW",
		"BLOW",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		HWND_MESSAGE,
		NULL,
		GetModuleHandle(NULL),
		NULL
		);
	if (!hwnd)
		throw CWinException();
	AutoCloseWindow autoCloseWindow(hwnd);
	CNotifyIcon notifyIcon(hwnd);

	MSG msg;
	while (true)
	{
		switch (GetMessage(&msg, NULL, 0, 0))
		{
		case 0:
			return;
		case -1:
			throw CWinException();
		default:
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
	}
}
