#include "ChildWnd.h"

TCHAR			g_szChildClassName[]	= TEXT("WirelessViewChildWndClass");


VOID DefineChildWndClass(LPWNDCLASSEX lpWc)
{
	lpWc->cbSize			= sizeof(WNDCLASSEX);
	lpWc->style				= CS_HREDRAW | CS_VREDRAW;
	lpWc->lpfnWndProc		= MDIChildWndProc;
	lpWc->cbClsExtra		= 0;
	lpWc->cbWndExtra		= sizeof(LPCONNECTION);
	lpWc->hIcon				= LoadIcon(lpWc->hInstance, MAKEINTRESOURCE(IDI_CHILD_ICON));
	lpWc->hCursor			= LoadCursor(NULL, IDC_ARROW);
	lpWc->hbrBackground		= (HBRUSH)(COLOR_WINDOW+1);
	lpWc->lpszMenuName		= NULL;
	lpWc->lpszClassName		= g_szChildClassName;
	lpWc->hIconSm			= LoadIcon(lpWc->hInstance, MAKEINTRESOURCE(IDI_CHILD_ICON));
}

HWND CreateMDIChild(HWND hMDIClient, LPCONNECTION lpCon)
{
	MDICREATESTRUCT mcs;
	HWND hChild;

	mcs.szTitle = TEXT("[Untitled]");
	mcs.szClass = g_szChildClassName;
	mcs.hOwner  = GetModuleHandle(NULL);
	mcs.x = mcs.cx = CW_USEDEFAULT;
	mcs.y = mcs.cy = CW_USEDEFAULT;
	mcs.style = MDIS_ALLCHILDSTYLES;
	mcs.lParam = (LPARAM) lpCon;

	hChild = (HWND)SendMessage(hMDIClient, WM_MDICREATE, 0, (LONG)&mcs);
	if(!hChild)
	{
		MessageBox(hMDIClient, TEXT("MDI Child creation failed."), TEXT("Oh Oh..."),
			MB_ICONEXCLAMATION | MB_OK);
	}
	return hChild;
}

LRESULT CALLBACK MDIChildWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch(msg)
	{	
	case WM_CREATE:
		{			
			LPMDICREATESTRUCT	lpMcs	= (LPMDICREATESTRUCT) (((LPCREATESTRUCT) lParam)->lpCreateParams);			
			LPCONNECTION		lpMyCc	= (LPCONNECTION)(lpMcs->lParam);		

			SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)lpMyCc);

			((LPCLIENTDATA)GetProtocolDataPtr(lpMyCc))->hWndClient = hwnd;
			((LPCLIENTDATA)GetProtocolDataPtr(lpMyCc))->hWndVideo = CreateWindowEx(0, g_szVideoWndClassName, NULL,
				WS_CHILD | WS_VISIBLE , 
				0,0,
				640,480,
				hwnd, NULL, g_hInstance, NULL);
			
		}
		break;			
	case WM_MDIACTIVATE:
	{
		UINT	EnableFlag;
		HWND	hWndFrame = GetParent(GetParent(hwnd));
		HMENU	hMenu = GetMenu(hWndFrame);

		EnableFlag = (hwnd == (HWND)lParam)?MF_ENABLED : MF_GRAYED;		
		EnableMenuItem(hMenu, 2, MF_BYPOSITION | EnableFlag);
		DrawMenuBar(hWndFrame);
	}
		break;

	case WM_CLOSE:
		{
			LPCONNECTION lpCon = (LPCONNECTION)GetWindowLongPtr(hwnd, GWLP_USERDATA);
			PostIOCPMessage(lpCon, IOCPMSG_BEGINDISCONNECT);
		}
		break;
	case WVM_DESTROYME:
		{
			DestroyWindow(hwnd);
		}
		return 0;
	case WM_ERASEBKGND:
		return 0;
	case WM_SIZE:
		{
			LPCONNECTION lpCon = (LPCONNECTION) GetWindowLongPtr(hwnd, GWLP_USERDATA);			
			MoveWindow(((LPCLIENTDATA)GetProtocolDataPtr(lpCon))->hWndVideo, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE);
			return DefMDIChildProc(hwnd, msg, wParam, lParam);
		}
	default:
		return DefMDIChildProc(hwnd, msg, wParam, lParam);	
	}
	return 0;
}

