#include "Wumbo-Header.h"
#if PLATFORM_WINDOWS || PLATFORM_OSX

#if PLATFORM_WINDOWS
#include <GL/glew.h>
#include <windows.h>
#include <gl/gl.h>
#endif

#include "Wumbo-WindowsRoot.h"
#include "Wumbo-Program.h"
#include "Wumbo-InputManager.h"
#include "Wumbo-Scene.h"
#include "Wumbo-KeyboardInput.h"
#include "Wumbo-Renderer.h"
#include "Wumbo-VirtualRenderTarget.h"

void Wumbo::WindowsRoot::go(Wumbo::Program *prog)
{
	program = prog;
	program->setSFMLWindow(new sf::RenderWindow(sf::VideoMode(1,1,32),sf::String("Lemons"),sf::Style::Close,sf::ContextSettings(0,0,0,2,1)));
	//program->getSFMLWindow()->ce
#if PLATFORM_WINDOWS
	glewInit();
#endif
	 
	glViewport(0,0,program->getSFMLWindow()->getSize().x,program->getSFMLWindow()->getSize().y);
	glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	program->begin();

	program->getInputManager()->update();
	program->update();
	program->getRenderer()->resetVirtualRenderTarget();
	program->render();
	program->getSFMLWindow()->display();
	program->getSFMLWindow()->setKeyRepeatEnabled(false);


	clock_t timeSinceLastFrame = clock();

	bool loop = true;
	while(loop)
	{
		if (program->getRenderer() == NULL)
		{
			FATALMSG("Program has no Renderer! ... Dying.")
			loop = false;
			break;
		}

		sf::Event event;
		while(program->getSFMLWindow()->pollEvent(event))
		{
			if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased)
			{
				if (program->getInputManager() != NULL)
					if (program->getInputManager()->getReceiveKeyboardUpdates())
						program->getInputManager()->getKeyboardState()->handleEvent(event);
			}
			/*if (event.type == sf::Event::MouseButtonPressed || event.type == sf::Event::MouseButtonReleased || event.type == sf::Event::MouseMoved)
			{
				if (inputManager->getReceiveMouseUpdates())
					inputManager->getMouseState()->handleEvent(event);
			}*/
			if (event.type == sf::Event::Closed)
				program->getSFMLWindow()->close();
		}
		if (!program->getSFMLWindow()->isOpen())
		{
			if (program->getScene() != NULL)
				program->getScene()->end();
			loop = false;
			break;
		}
		program->getInputManager()->update();
		program->update();

		program->getRenderer()->resetVirtualRenderTarget();
		program->render();
		program->getSFMLWindow()->display();
		if (program->getInputManager() != NULL)
			if (program->getInputManager()->getReceiveKeyboardUpdates())
				program->getInputManager()->getKeyboardState()->onEndOfFrame();

#if PLATFORM_WINDOWS
		int t = 1000/program->getAssignedFrameRate() - 1000*((clock()-timeSinceLastFrame)/CLOCKS_PER_SEC);
		if (t > 0)
		{
			Sleep(t);//      CLOCKS_PER_SEC/program->getAssignedFrameRate()
		}
		timeSinceLastFrame = clock();
#endif
	}
}
#endif