#include "ShadowApp.h"

ShadowApp* g_App;

long FAR PASCAL MainWndproc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
	switch (message)
    {
		case WM_ACTIVATEAPP:
			g_App->SetActive((bool) wParam);

            return TRUE;
		case WM_KEYDOWN:
            // Handle any non-accelerated key commands
           switch (wParam)
            {
                case VK_ESCAPE: g_App->Exit();
            }
            break;

		case WM_SYSCOMMAND:
        // Prevent moving/sizing and power loss
			switch( wParam )
			{
				case SC_MOVE:
				case SC_SIZE:
				case SC_MAXIMIZE:
				case SC_KEYMENU:
				case SC_MONITORPOWER: //screensaver
					if( !g_App->GetCurrentMode().Windowed )
                        return 0;
			}
			break;

		case WM_SETCURSOR:
			if (LOWORD(lParam) == HTCLIENT)
			{
				//SetCursor(g_App->GetDI()->GetCursor());
				if (g_App->GetDI()->GetDeviceCursor())
				{
					g_App->GetDevice()->GetDevice()->ShowCursor(g_App->GetDI()->IsMouseVisible());
				}
				//g_App->GetDevice()->GetDevice()->ShowCursor( TRUE );
				//wlog("set");
				return 0;
			}
			break;
		
		case WM_SIZE:
			//cxClient = LOWORD(lParam);
			//cyClient = HIWORD(lParam);
			return 0;

		case WM_EXITSIZEMOVE:
        
			if (g_App->GetCurrentMode().Windowed)
			{
				g_App->Reset3D(g_App->GetCurrentMode());
			}
                    
            break;

		case WM_MOUSEMOVE:
			POINT pnt;
            GetCursorPos(&pnt);
            g_App->GetDevice()->GetDevice()->SetCursorPosition(pnt.x, pnt.y, 0);
			//g_App->GetDevice()->GetDevice()->SetCursorPosition(g_App->GetDI()->GetMouseScreenX(), g_App->GetDI()->GetMouseScreenY(), D3DCURSOR_IMMEDIATE_UPDATE);
			break;

		case WM_NCHITTEST:
            // Prevent the user from selecting the menu in full screen mode
            if( !g_App->GetCurrentMode().Windowed)
                return HTCLIENT;
            break;

        case WM_CLOSE:
            PostQuitMessage(0);
            return 0L;
	}
    return DefWindowProc(hWnd, message, wParam, lParam);
} 

int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine,int nCmdShow )
{
	#ifdef _DEBUG
	_CrtMemState s1, s2, s3;

	_CrtMemCheckpoint( &s1 );
	#endif

	g_App = new ShadowApp();

	if(g_App->Init(hInstance) == S_OK)
		g_App->Run();

	delete g_App;

	#ifdef _DEBUG
	_CrtMemCheckpoint( &s2 );

	_CrtDumpMemoryLeaks();

	if ( _CrtMemDifference( &s3, &s1, &s2) )
		_CrtMemDumpStatistics( &s3 );
	#endif
}