#include <stdio.h>
#include <iostream>
#include <fstream>

#include "anki/input/Input.h"
#include "anki/scene/Camera.h"
#include "anki/math/Math.h"
#include "anki/renderer/Renderer.h"
#include "anki/core/App.h"
#include "anki/resource/Mesh.h"
#include "anki/scene/Light.h"
#include "anki/resource/Material.h"
#include "anki/scene/Scene.h"
#include "anki/resource/SkelAnim.h"
#include "anki/physics/Character.h"
#include "anki/renderer/Renderer.h"
#include "anki/renderer/MainRenderer.h"
#include "anki/physics/Character.h"
#include "anki/physics/RigidBody.h"
#include "anki/script/ScriptManager.h"
#include "anki/core/StdinListener.h"
#include "anki/scene/ModelNode.h"
#include "anki/resource/Model.h"
#include "anki/core/Logger.h"
#include "anki/util/Filesystem.h"
#include "anki/util/HighRezTimer.h"
#include "anki/scene/SkinNode.h"
#include "anki/resource/Skin.h"
#include "anki/event/EventManager.h"
#include "anki/event/SceneColorEvent.h"
#include "anki/event/MainRendererPpsHdrEvent.h"
#include "anki/resource/ShaderProgramPrePreprocessor.h"
#include "anki/resource/Material.h"
#include "anki/core/ThreadPool.h"
#include "anki/core/Timestamp.h"
#include "anki/core/NativeWindow.h"
#include "anki/util/Functions.h"
#include "anki/scene/ParticleEmitter.h"

using namespace anki;

ModelNode* horse;
PerspectiveCamera* cam;
NativeWindow* win;

//==============================================================================
void initPhysics()
{
	Scene& scene = SceneSingleton::get();

	scene.getPhysics().setDebugDrawer(
		new PhysicsDebugDrawer(
			&MainRendererSingleton::get().getDbg().getDebugDrawer()));

	btCollisionShape* groundShape = new btBoxShape(
	    btVector3(btScalar(50.), btScalar(50.), btScalar(50.)));

	Transform groundTransform;
	groundTransform.setIdentity();
	groundTransform.setOrigin(Vec3(0, -50, 0));

	RigidBody::Initializer init;
	init.mass = 0.0;
	init.shape = groundShape;
	init.startTrf = groundTransform;
	init.group = PhysWorld::CG_MAP;
	init.mask = PhysWorld::CG_ALL;

	new RigidBody(&SceneSingleton::get().getPhysics(), init);

#if 1
	btCollisionShape* colShape = new btBoxShape(
	    btVector3(1, 1, 1));

	init.startTrf.setOrigin(Vec3(0.0, 15.0, 0.0));
	init.mass = 20;
	init.shape = colShape;
	init.group = PhysWorld::CG_PARTICLE;
	init.mask = PhysWorld::CG_MAP | PhysWorld::CG_PARTICLE;

	const I ARRAY_SIZE_X = 5;
	const I ARRAY_SIZE_Y = 5;
	const I ARRAY_SIZE_Z = 5;
	const I START_POS_X = -5;
	const I START_POS_Y = 35;
	const I START_POS_Z = -3;

	float start_x = START_POS_X - ARRAY_SIZE_X / 2;
	float start_y = START_POS_Y;
	float start_z = START_POS_Z - ARRAY_SIZE_Z / 2;

	for(I k = 0; k < ARRAY_SIZE_Y; k++)
	{
		for(I i = 0; i < ARRAY_SIZE_X; i++)
		{
			for(I j = 0; j < ARRAY_SIZE_Z; j++)
			{
				std::string name = std::string("crate0") + std::to_string(i)
					+ std::to_string(j) + std::to_string(k);

				ModelNode* mnode = new ModelNode(
					"data/models/crate0/crate0.mdl",
					name.c_str(),
					&SceneSingleton::get(), Movable::MF_NONE, nullptr);

				init.movable = mnode;
				ANKI_ASSERT(init.movable);

				Transform trf(
					Vec3(2.0 * i + start_x, 2.0 * k + start_y,
						2.0 * j + start_z), Mat3::getIdentity(), 1.0);

				init.startTrf = trf;

				new RigidBody(&SceneSingleton::get().getPhysics(), init);
			}
		}
	}
#endif
}

//==============================================================================
void init()
{
	ANKI_LOGI("Other init...");

	Scene& scene = SceneSingleton::get();

#if 0
	painter = new UiPainter(Vec2(AppSingleton::get().getWindowWidth(),
		AppSingleton::get().getWindowHeight()));
	painter->setFont("engine-rsrc/ModernAntiqua.ttf", 25, 25);
#endif

	// camera
	cam = new PerspectiveCamera("main-camera", &scene,
		Movable::MF_NONE, nullptr);
	const F32 ang = 45.0;
	cam->setAll(
		MainRendererSingleton::get().getAspectRatio() * toRad(ang),
		toRad(ang), 0.5, 500.0);
	cam->setLocalTransform(Transform(Vec3(82.0, 5.0, 8.0),
		Mat3(Euler(toRad(-10.0), toRad(90.0), toRad(0.0))),
		1.0));
	scene.setActiveCamera(cam);

	// camera 2
	PerspectiveCamera* pcam = new PerspectiveCamera("camera1", &scene,
		Movable::MF_NONE, nullptr);
	pcam->setAll(
		MainRendererSingleton::get().getAspectRatio() * toRad(ang),
		toRad(ang), 0.5, 200.0);
	pcam->setLocalTransform(Transform(Vec3(100.0, 3.0, 8.0),
		Mat3(Axisang(toRad(90.0), Vec3(0, 1, 0))),
		1.0));

	// lights
#if 1
	Vec3 lpos(-90.0, 1.2, -32.0);
	for(int i = 0; i < 50; i++)
	{
		for(int j = 0; j < 10; j++)
		{
			std::string name = "plight" + std::to_string(i) + std::to_string(j);

			PointLight* point = new PointLight(name.c_str(), &scene,
				Movable::MF_NONE, nullptr);
			point->setRadius(2.0);
			point->setDiffuseColor(Vec4(randFloat(6.0) - 2.0, 
				randFloat(6.0) - 2.0, randFloat(6.0) - 2.0, 0.0));
			point->setSpecularColor(Vec4(randFloat(6.0) - 3.0, 
				randFloat(6.0) - 3.0, randFloat(6.0) - 3.0, 0.0));
			point->setLocalTranslation(lpos);

			lpos.z() += 7.0;
		}

		lpos.x() += 3.5;
		lpos.z() = -32;
	}
#endif

#if 1
	SpotLight* spot = new SpotLight("spot0", &scene, Movable::MF_NONE, nullptr);
	spot->setOuterAngle(toRad(45.0));
	spot->setInnerAngle(toRad(15.0));
	spot->setLocalTransform(Transform(Vec3(1.3, 4.3, 3.0),
		Mat3::getIdentity(), 1.0));
	spot->setDiffuseColor(Vec4(2.0));
	spot->setSpecularColor(Vec4(-1.0));
	spot->loadTexture("gfx/lights/flashlight.tga");
	spot->setDistance(30.0);
	spot->setShadowEnabled(true);


	spot = new SpotLight("spot1", &scene, Movable::MF_NONE, nullptr);
	spot->setOuterAngle(toRad(45.0));
	spot->setInnerAngle(toRad(15.0));
	spot->setLocalTransform(Transform(Vec3(5.3, 4.3, 3.0),
		Mat3::getIdentity(), 1.0));
	spot->setDiffuseColor(Vec4(3.0, 0.0, 0.0, 0.0));
	spot->setSpecularColor(Vec4(3.0, 3.0, 0.0, 0.0));
	spot->loadTexture("gfx/lights/flashlight.tga");
	spot->setDistance(30.0);
	spot->setShadowEnabled(true);
#endif

	// Vase point lights
	Array<Vec3, 4> vaseLightPos = {{Vec3(32.6, 9, -13.2), Vec3(32.6, 9, 10),
		Vec3(-37.6001, 9, 10), Vec3(-37.6001, 9, -13.2)}};
	for(U i = 0; i < vaseLightPos.getSize(); i++)
	{
		PointLight* point =
			new PointLight(("vase_plight" + std::to_string(i)).c_str(),
			&scene, Movable::MF_NONE, nullptr);
		point->setRadius(3.5);
		point->setLocalTranslation(vaseLightPos[i]);
		point->setDiffuseColor(Vec4(3.0, 0.0, 0.0, 0.0));
		point->setSpecularColor(Vec4(1.0, 1.0, 0.0, 0.0));

		ParticleEmitter* pe = new ParticleEmitter(
			"data/particles/smoke.particles",
			("pe" + std::to_string(i)).c_str(), &scene,
			Movable::MF_NONE, nullptr);
		pe->setLocalTranslation(vaseLightPos[i]);

		pe = new ParticleEmitter(
			"data/particles/fire.particles",
			("pef" + std::to_string(i)).c_str(), &scene,
			Movable::MF_NONE, nullptr);
		pe->setLocalTranslation(vaseLightPos[i]);
	}

	/*PointLight* point1 = new PointLight("point1", &scene, Movable::MF_NONE,
		nullptr);
	point1->setRadius(3.0);
	point1->setDiffuseColor(Vec4(2.0, 2.0, 2.0, 0.0));
	point1->setSpecularColor(Vec4(3.0, 3.0, 0.0, 0.0));
	point1->setLocalTranslation(Vec3(-3.0, 2.0, 0.0));*/

	// horse
	horse = new ModelNode("data/models/horse/horse.mdl", "horse", &scene,
		Movable::MF_NONE, nullptr);
	horse->setLocalTransform(Transform(Vec3(-2, 0, 0), Mat3::getIdentity(),
		1.0));

#if 0
	// Sponza
	ModelNode* sponzaModel = new ModelNode(
		"maps/sponza-crytek/sponza_crytek.mdl",
		"sponza", &scene, Movable::MF_NONE, nullptr);

	sponzaModel->setLocalScale(0.1);

	// Sectors
	Aabb sectorAabb;
	sponzaModel->getModel().getVisibilityShape().toAabb(sectorAabb);
	scene.sectors.push_back(new Sector(sectorAabb));
#endif

#if 1
	ModelNode* sponzaModel = new ModelNode(
		"data/maps/sponza/sponza.mdl",
		"sponza", &scene, Movable::MF_NONE, nullptr);

	(void)sponzaModel;
#endif

	initPhysics();

	/*ParticleEmitter* pe = new ParticleEmitter("todo", "pe", &scene,
		Movable::MF_NONE, nullptr);
	(void)pe;*/
}

//==============================================================================
/// The func pools the stdinListener for string in the console, if
/// there are any it executes them with scriptingEngine
void execStdinScpripts()
{
	while(1)
	{
		std::string cmd = StdinListenerSingleton::get().getLine();

		if(cmd.length() < 1)
		{
			break;
		}

		try
		{
			ScriptManagerSingleton::get().evalString(cmd.c_str());
		}
		catch(Exception& e)
		{
			ANKI_LOGE(e.what());
		}
	}
}

//==============================================================================
void mainLoopExtra()
{
	F32 dist = 0.2;
	F32 ang = toRad(3.0);
	F32 scale = 0.01;
	F32 mouseSensivity = 9.0;

	// move the camera
	static Movable* mover = SceneSingleton::get().getActiveCamera().getMovable();
	Input& in = InputSingleton::get();

	if(in.getKey(KC_1))
	{
		mover = &SceneSingleton::get().getActiveCamera();
	}
	if(in.getKey(KC_2))
	{
		mover = SceneSingleton::get().findSceneNode("horse").getMovable();
	}
	if(in.getKey(KC_3))
	{
		mover = SceneSingleton::get().findSceneNode("spot0").getMovable();
	}
	if(in.getKey(KC_4))
	{
		mover = SceneSingleton::get().findSceneNode("spot1").getMovable();
	}
	if(in.getKey(KC_5))
	{
		mover = SceneSingleton::get().findSceneNode("pe").getMovable();
	}
	if(in.getKey(KC_6))
	{
		mover = SceneSingleton::get().findSceneNode("vase_plight0").getMovable();
	}

	if(in.getKey(KC_L) == 1)
	{
		Light* l = SceneSingleton::get().findSceneNode("point1").getLight();
		static_cast<PointLight*>(l)->setRadius(10.0);
	}

	if(in.getKey(KC_P) == 1)
	{
		//MainRendererSingleton::get().getPps().getHdr().setExposure(20);
		//in.hideCursor(true);
		MainRendererSingleton::get().getDbg().setDepthTestEnabled(
			!MainRendererSingleton::get().getDbg().getDepthTestEnabled());
	}

	if(in.getKey(KC_UP)) mover->rotateLocalX(ang);
	if(in.getKey(KC_DOWN)) mover->rotateLocalX(-ang);
	if(in.getKey(KC_LEFT)) mover->rotateLocalY(ang);
	if(in.getKey(KC_RIGHT)) mover->rotateLocalY(-ang);

	if(in.getKey(KC_A)) mover->moveLocalX(-dist);
	if(in.getKey(KC_D)) mover->moveLocalX(dist);
	if(in.getKey(KC_Z)) mover->moveLocalY(dist);
	if(in.getKey(KC_SPACE)) mover->moveLocalY(-dist);
	if(in.getKey(KC_W)) mover->moveLocalZ(-dist);
	if(in.getKey(KC_S)) mover->moveLocalZ(dist);
	if(in.getKey(KC_Q)) mover->rotateLocalZ(ang);
	if(in.getKey(KC_E)) mover->rotateLocalZ(-ang);
	if(in.getKey(KC_PAGEUP))
	{
		mover->scale(scale);
	}
	if(in.getKey(KC_PAGEDOWN))
	{
		mover->scale(-scale);
	}
	if(in.getKey(KC_P))
	{
		ANKI_LOGI("pos: " << mover->getWorldTransform().getOrigin());
	}


	mover->rotateLocalY(-ang * in.getMousePosition().x() * mouseSensivity * 
		MainRendererSingleton::get().getAspectRatio());
	mover->rotateLocalX(ang * in.getMousePosition().y() * mouseSensivity);

	execStdinScpripts();
}

//==============================================================================
void mainLoop()
{
	ANKI_LOGI("Entering main loop");

	HighRezTimer mainLoopTimer;
	mainLoopTimer.start();
	HighRezTimer::Scalar prevUpdateTime = HighRezTimer::getCurrentTime();
	HighRezTimer::Scalar crntTime = prevUpdateTime;

	while(1)
	{
		HighRezTimer timer;
		timer.start();

		prevUpdateTime = crntTime;
		crntTime = HighRezTimer::getCurrentTime();

		// Update
		//
		InputSingleton::get().handleEvents();
		InputSingleton::get().moveMouse(Vec2(0.0));
		mainLoopExtra();
		SceneSingleton::get().update(
			prevUpdateTime, crntTime, MainRendererSingleton::get());
		EventManagerSingleton::get().updateAllEvents(prevUpdateTime, crntTime);
		MainRendererSingleton::get().render(SceneSingleton::get());

		if(InputSingleton::get().getKey(KC_ESCAPE))
		{
			break;
		}

		win->swapBuffers();

		// Sleep
		//
#if 1
		timer.stop();
		if(timer.getElapsedTime() < AppSingleton::get().getTimerTick())
		{
			HighRezTimer::sleep(AppSingleton::get().getTimerTick()
				- timer.getElapsedTime());
		}
#else
		if(MainRendererSingleton::get().getFramesCount() == 1000)
		{
			break;
		}
#endif
		Timestamp::increaseTimestamp();
	}

#if 1
	MainRendererSingleton::get().takeScreenshot("screenshot.tga");
#endif

	ANKI_LOGI("Exiting main loop (" << mainLoopTimer.getElapsedTime()
		<< " sec)");
}

//==============================================================================
// initSubsystems                                                              =
//==============================================================================
void initSubsystems(int argc, char* argv[])
{
#if ANKI_GL == ANKI_GL_DESKTOP
	U32 glmajor = 3;
	U32 glminor = 3;
#else
	U32 glmajor = 3;
	U32 glminor = 0;
#endif

	// App
	AppSingleton::get().init(argc, argv);

	// Window
	NativeWindowInitializer nwinit;
	nwinit.width = 1280;
	nwinit.height = 720;
	nwinit.majorVersion = glmajor;
	nwinit.minorVersion = glminor;
	nwinit.depthBits = 0;
	nwinit.stencilBits = 0;
	win = new NativeWindow;	
	win->create(nwinit);

	// GL stuff
	GlStateCommonSingleton::get().init(glmajor, glminor);

	// Input
	InputSingleton::get().init(win);
	InputSingleton::get().hideCursor(true);

	// Main renderer
	RendererInitializer initializer;
	initializer.ms.ez.enabled = true;
	initializer.dbg.enabled = false;
	initializer.is.sm.bilinearEnabled = true;
	initializer.is.groundLightEnabled = false;
	initializer.is.sm.enabled = true;
	initializer.is.sm.pcfEnabled = false;
	initializer.is.sm.resolution = 512;
	initializer.pps.hdr.enabled = true;
	initializer.pps.hdr.renderingQuality = 0.25;
	initializer.pps.hdr.blurringDist = 1.0;
	initializer.pps.hdr.blurringIterationsCount = 2;
	initializer.pps.hdr.exposure = 8.0;
	initializer.pps.ssao.blurringIterationsNum = 4;
	initializer.pps.ssao.enabled = true;
	initializer.pps.ssao.mainPassRenderingQuality = 0.3;
	initializer.pps.ssao.blurringRenderingQuality = 0.5;
	initializer.pps.enabled = true;
	initializer.pps.bl.enabled = true;
	initializer.pps.bl.blurringIterationsNum = 2;
	initializer.pps.bl.sideBlurFactor = 1.0;
	initializer.renderingQuality = 1.0;
	initializer.width = nwinit.width;
	initializer.height = nwinit.height;

	MainRendererSingleton::get().init(initializer);

	// Stdin listener
	StdinListenerSingleton::get().start();

	// Parallel jobs
	ThreadPoolSingleton::get().init(8);
}

//==============================================================================
int main(int argc, char* argv[])
{
	int exitCode;

	try
	{
		initSubsystems(argc, argv);
		init();

		mainLoop();

		ANKI_LOGI("Exiting...");
		AppSingleton::get().quit(EXIT_SUCCESS);
		exitCode = 0;
	}
	catch(std::exception& e)
	{
		std::cerr << "Aborting: " << e.what() << std::endl;
		exitCode = 1;
	}
	ANKI_LOGI("Bye!!");
	return exitCode;
}
