#include "Application.h"

#include "Utilities/CfgParser.h"
#include "Utilities/Log.h"

#include "ScriptSystem_Application.h"
#include "ScriptSystem_Camera.h"
#include "ScriptSystem_Font.h"
#include "ScriptSystem_Image.h"
#include "ScriptSystem_Math.h"
#include "ScriptSystem_RigidBody.h"
#include "ScriptSystem_SceneGraph.h"
#include "ScriptSystem_SceneNode.h"
#include "ScriptSystem_Model.h"

namespace BlueCore
{

void Application::KeySlot(int key, int action)
{
	if (key == GLFW_KEY_ESC && action == GLFW_RELEASE)
		quit();
}

void Application::MouseMoveSlot(int x, int y)
{
	_CameraPhi += (x - _LastMouseX) / 200.0;
	_LastMouseX = x;

	_CameraTheta += (y - _LastMouseY) / 200.0;
	_LastMouseY = y;
}

void Application::MouseWheelSlot(int z)
{
	if ((z - _LastWheel) < 0)
		_CameraRadius *= 2.0;
	else
		_CameraRadius *= 0.5;

	if (_CameraRadius < 1.0)
		_CameraRadius = 1.0;

	_LastWheel = z;
}

bool Application::initialize()
{
	CfgParser cfg;
	cfg.parseFile("options.cfg");

	int width = cfg.get("width", 640);
	int height = cfg.get("height", 480);
	bool fullscreen = cfg.get("fullscreen", false);

	_Window = new RenderWindow();
	if (_Window->create(width, height, 0, 0, 0, fullscreen) == false)
		return false;

	_Device = new RenderDevice(_Window);
	_FontManager = new FontManager(_Device);
	_MeshManager = new MeshManager(_Device);
	_TextureManager = new TextureManager();
	_ScriptSystem = new ScriptSystem();
	_ShaderManager = new ShaderManager(_Window);
	_Simulation = new RigidBodySimulation(_ScriptSystem);
	_ModelManager = new ModelManager (_TextureManager, _ShaderManager, _MeshManager);
	_RenderQueue = new RenderQueue();

	setupScriptSystem_Application(_ScriptSystem, this);
	setupScriptSystem_Camera(_ScriptSystem);
	setupScriptSystem_Font(_ScriptSystem, _FontManager);
	setupScriptSystem_Image(_ScriptSystem, _TextureManager, _Device);
	setupScriptSystem_Math(_ScriptSystem);
	setupScriptSystem_RigidBody(_ScriptSystem, _Simulation);
	setupScriptSystem_SceneGraph(_ScriptSystem);
	setupScriptSystem_SceneNode(_ScriptSystem);
	setupScriptSystem_Model(_ScriptSystem, _ModelManager);

	if (_ScriptSystem->loadScript("main") == false)
		return false;

	_ScriptSystem->callFunction("Initialize");

	_Window->KeySignal.connect(this, &Application::KeySlot);
	_Window->MouseMoveSignal.connect(this, &Application::MouseMoveSlot);
	_Window->MouseWheelSignal.connect(this, &Application::MouseWheelSlot);

	_Running = true;

	return true;
}

void Application::shutdown()
{
	_ScriptSystem->callFunction("Shutdown");
}

void Application::quit()
{
	_Running = false;
}

void Application::run()
{
	clog << "--- starting main loop..."<< endlog;

	_SimulationTime = 0.0;
	_StartTime = glfwGetTime();
	_LastTime = _StartTime;

	double delta = 0.0;

	_Paused = false;
	_Running = true;

	ref_ptr<Mesh> star_mesh = _MeshManager->loadMesh ("stars.3ds");
	ref_ptr<Texture> star_texture = _TextureManager->loadTexture ("stars.png", 0);

	GLfloat lightAmbient[]  = {0.0f, 0.0f, 0.0f, 1.0f} ;
	GLfloat lightDiffuse[]  = {1.0f, 1.0f, 1.0f, 1.0f} ;
	GLfloat lightSpecular[] = {1.0f, 1.0f, 1.0f, 1.0f} ;
	GLfloat lightPosition[] = { 1.0, 0.0, 0.0, 0.0};

	glLightfv ( GL_LIGHT0, GL_AMBIENT, lightAmbient ) ;
	glLightfv ( GL_LIGHT0, GL_DIFFUSE, lightDiffuse ) ;
	glLightfv ( GL_LIGHT0, GL_SPECULAR, lightSpecular ) ;
	glLightfv ( GL_LIGHT0, GL_POSITION, lightPosition );

	glEnable ( GL_LIGHT0 ) ;
	
	while (_Window->isOpen() && _Running)
	{
		double now = glfwGetTime();
		delta = now - _LastTime;
		_LastTime = now;

		_ScriptSystem->callFunction("OnFrame", delta, now - _StartTime);

		_Device->clear();

		//Quaternion q(-_CameraPhi, 0.0, -_CameraTheta);
		//camera->setPosition(q.apply(Vector3(0.0, 0.0, _CameraRadius)));
		//camera->setRotation(q);
		//pos += 5 * _DeltaTime;
		 _Device->setAmbientLight(1.0, 1.0, 1.0);

		if (_SceneGraph.valid())
		{
			_RenderQueue->clear();
			_SceneGraph->update(delta);
			_SceneGraph->queue(_RenderQueue);
			_Device->begin3D(_SceneGraph->getCamera());
			_RenderQueue->render(_Device);
			_Device->end3D();
		}
		/*
		 {
		 _Device->begin3D(_Camera);
		 _RenderQueue->clear();
		 _RenderQueue->addOpaqueItem(model, Vector3(0.0, 0.0, 0.0),
		 Quaternion());
		 _RenderQueue->render(_Device);
		 _Device->end3D();
		 }
		 */
		/*
			 */
		// device->useShader (program);
		// device->setTexture (stage, name, texture)
		// device->clearTextures (stage+1);
		//glEnable (GL_TEXTURE_2D);
		//glEnable (GL_LIGHTING);
		//glBindTexture (GL_TEXTURE_2D, texture->getId() );

		// device->
		//device->
		//model->render();
		if (_Paused == false)
		{
			_Simulation->saveStates();
			_Simulation->updateSteps(delta);
			while (_Simulation->getSteps() > 0)
			{
				_ScriptSystem->callFunction("OnStep",
						_Simulation->getStepSize(), _SimulationTime);
				_SimulationTime += _Simulation->getStepSize();
				_Simulation->step();
			}
		}

		_Device->pushAbsoluteTransformation(Vector3(), _SceneGraph->getCamera()->getRotation());
/*
		_Device->setShaderProgram (0);
		 glEnable(GL_DEPTH_TEST);
		 glDepthMask(GL_FALSE);
*/
		 glDisable(GL_BLEND);
		 glEnable(GL_DEPTH_TEST);
		 _Device->setTexture(0, star_texture, true);
		 glDisable(GL_LIGHTING);
		 glColor4d( 1.0f, 1.0f, 1.0f, 1.0f);
		 star_mesh->render();
		 _Device->popTransformation();

		/*
			 class RenderState
			 {
			 bool _Blending;
			 GLint _BlendFuncSrc;
			 GLint _BlendFuncDest;

			 bool _DepthTest;
			 bool _DepthMask;

			 bool _Lighting;
			 };
			 GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
			 GLfloat mat_shininess[] = { 2.0 };
			 glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_specular);
			 glMaterialfv(GL_FRONT, GL_AMBIENT, mat_specular);
			 glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
			 glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
*/
		
		_Device->begin2D();
		_ScriptSystem->callFunction("OnOverlay", delta, now - _StartTime);
		_Device->end2D();

		_Device->swap();
	}

	clog << "--- main loop finished..."<< endlog;
}

void Application::setSceneGraph(SceneGraph *graph)
{
	_SceneGraph = graph;
}

void Application::togglePause()
{
	_Paused = !_Paused;
}
}

