#include "GameCore.h"
#include "GameWindow.h"
#include "RPGXEngine.h"
#include "ScreenManager.h"
#include "Timing.h"

//-----[ WinMain ]--------------------------------------------
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
					 LPSTR lpCmdLine, int nShowCmd)
{
	
	static char appTitle[] = "Tirian Journey";
	static char windowTitle[] = "Tirian Journey";
	//make a game window
	GameWindow gameWindow;
	gameWindow.SetWindowSize(0,0,ScreenManager::getWindowWidth(),ScreenManager::getWindowHeight());
	gameWindow.MyRegisterClass(hInstance, appTitle);
	if (!gameWindow.InitInstance(hInstance, nShowCmd, appTitle, windowTitle))
	{
		GameError("Error Creating Window");	
		return E_FAIL;
	}

	//setup timing and tie it to our window
	Timing timer;
	HRESULT r = timer.SetupTiming();
    if (FAILED(r))
	{
		GameError("Error Setting Up Timing Structure");
		return r;
	}

	//setup DirectX and tie it to our window
	RPGXEngine gameEngine( &timer, hInstance, gameWindow.getHwnd() );
	r = gameEngine.setupD3D(gameWindow.getHwnd());
	if (FAILED(r))
	{
		GameError("Error Setting Up Direct3D");
		return r;
	}

	//enter message loop and sit --------------
	MSG msg;
	int timesThroughLoop = 0;
	bool tick = false;
	while( true )
	{
	//check and see if there is a message
		if (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE))
		{
			//check and see if this is the quit message
			if (msg.message == WM_QUIT)
				//exit the message loop
				break;
			//else do what we would have before, namely translate and dispatch
			TranslateMessage( &msg );
			DispatchMessage( &msg );

		}
		else
		{
			//idle code LIKE A GAME LOOP...
			timer.SetStartTime();

			//RENDER LOOP --------------
			gameEngine.getDeviceHandle()->Clear( 0, 0, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 0, 25, 50), 0.0f, 0);
			
			gameEngine.getDeviceHandle()->BeginScene();
			if ( timesThroughLoop > timer.GetFrameRate() / 40 ) {
				tick = true;
				timesThroughLoop = 0;
			}
			gameEngine.gameLoop( tick ); //draw 2D stuff here...
			tick = false;
			timesThroughLoop++;
			gameEngine.getDeviceHandle()->EndScene();
            //flip to screen
			//draw 2D overlay stuff here...
			gameEngine.getDeviceHandle()->Present(
				NULL,NULL,NULL,NULL);
			//END RENDER LOOP -----------

			//lame methodology of locking to frame rate,
		    //just so happens it wastes processor cycles
		    if ( LOCK_FRAME_RATE )
		    timer.Pause(timer.GetPauseTime());

			//calc for next frame...
			timer.CalcFrameCount();
		}
	}
	return (int) msg.wParam;
}
