#include "windowing.h"

HINSTANCE rWindowing::hInstance;

LRESULT CALLBACK WinProc(HWND, UINT, WPARAM, LPARAM);

LRESULT CALLBACK WinProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) //TEMP
{
	LRESULT lRet = 0; 
		
	switch (uMsg)
	{ 
	case WM_CLOSE:
        PostQuitMessage(0);
        break;
	case WM_KEYDOWN:
		switch(wParam) 
		{
			case VK_ESCAPE:
				PostQuitMessage(0);
				break;
		}
	default:
		lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); 
	}
    return lRet;
}


rWindowing::rWindowing()
{
	width = 0;
	height = 0;
}

rWindowing::~rWindowing()
{
	if(width == 0 || height == 0)
		return;
	Kill();
}

void rWindowing::SetHI(HINSTANCE hI)
{
	hInstance = hI;
}

void rWindowing::SetScreenParam(char windowName[], int x, int y, int d, bool fs)
{
	strcpy(WindowName, windowName);
	width = x;
	height = y;
	depth = d;
	
	bFullScreen = fs;
}

bool rWindowing::Create()
{
	if(width == 0 || height == 0)
		return false;

	DWORD dwStyle;
	WNDCLASS wndclass;
	memset(&wndclass, 0, sizeof(WNDCLASS));	
	wndclass.style = CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc = WinProc;						//FIXME : CALLBACK PROC!			
	wndclass.hInstance = hInstance;	
	wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
	wndclass.lpszClassName = WindowName;	
	
	RegisterClass(&wndclass);

	int result = true;
	if(bFullScreen)
	{
		dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
		DEVMODE dmSettings;									
		memset(&dmSettings,0,sizeof(dmSettings));		
		
		EnumDisplaySettings(NULL,ENUM_CURRENT_SETTINGS,&dmSettings);
		dmSettings.dmPelsWidth	= width;
		dmSettings.dmPelsHeight	= height;
		dmSettings.dmBitsPerPel = depth;
		dmSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
		result = ChangeDisplaySettings(&dmSettings, CDS_FULLSCREEN);
		ShowCursor(false);
	}
	else
		dwStyle = WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;

	RECT rWindow;
	rWindow.left	= 0;
	rWindow.right	= width;	
	rWindow.top	    = 0;				
	rWindow.bottom	= height;

	AdjustWindowRect(&rWindow, dwStyle, false);


	hWnd = CreateWindow(WindowName, WindowName, dwStyle, 0, 0,
						width, height, 
						NULL, NULL, hInstance, NULL);

	if(!hWnd && !result) return false;

	ShowWindow(hWnd, SW_SHOWNORMAL);
	UpdateWindow(hWnd);

	hDC = GetDC(hWnd);
	SetFocus(hWnd);	
	return true;
}

void rWindowing::Update()
{
	SwapBuffers(hDC);
}

void rWindowing::Kill()
{
	releaseSubSytem();
	ChangeDisplaySettings(NULL,0);
	ShowCursor(true);
	UnregisterClass(WindowName, hInstance);	
	width = 0;
	height = 0;
}