#include "main_code.h"

#ifdef TARGET_ANDROID
#include "android_api.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#include "include/Engine.h"

#include "main_code.h"

#ifndef TARGET_IOS
boost::shared_ptr<TMyApplication> App(new TMyApplication);
#endif

bool animPaused = false;


Eigen::Matrix3f quatToMatrix(Eigen::Vector4f q) {
	using namespace Eigen;
	Matrix3f result;
	double sqw = q(3)*q(3);
	double sqx = q(0)*q(0);
	double sqy = q(1)*q(1);
	double sqz = q(2)*q(2);
	// invs (inverse square length) is only required if quaternion is not already normalised
	double invs = 1 / (sqx + sqy + sqz + sqw);
	result(0, 0) = (sqx - sqy - sqz + sqw)*invs; // since sqw + sqx + sqy + sqz =1/invs*invs
	result(1, 1) = (-sqx + sqy - sqz + sqw)*invs;
	result(2, 2) = (-sqx - sqy + sqz + sqw)*invs;
	double tmp1 = q(0)*q(1);
	double tmp2 = q(2)*q(3);
	result(1, 0) = 2.0 * (tmp1 + tmp2)*invs;
	result(0, 1) = 2.0 * (tmp1 - tmp2)*invs;
	tmp1 = q(0)*q(2);
	tmp2 = q(1)*q(3);
	result(2, 0) = 2.0 * (tmp1 - tmp2)*invs;
	result(0, 2) = 2.0 * (tmp1 + tmp2)*invs;
	tmp1 = q(1)*q(2);
	tmp2 = q(0)*q(3);
	result(2, 1) = 2.0 * (tmp1 + tmp2)*invs;
	result(1, 2) = 2.0 * (tmp1 - tmp2)*invs;
	return result;
}

struct TOnClickTest
{
	void operator()()
	{

		//ResourceManager->ScriptManager.RunScript("5+5;");

		if (animPaused)
		{
			//animPaused = false;
			//ResourceManager->HalibutAnimationManager.StartAnimation("test_anim");
			//ResourceManager->HalibutAnimationManager.ShowAnimation("test_anim");
			//ResourceManager->SoundManager.PlayMusic("finalogg.ogg");

			//App->Match3Controller.Match3Field->StartAnimateChip(4,1);

			//App->Match3Controller.Match3Field->HighlightMatch3();
		}
		else
		{
			//animPaused = true;
			//ResourceManager->HalibutAnimationManager.StopAnimation("test_anim");
			//ResourceManager->HalibutAnimationManager.HideAnimation("test_anim");
			//ResourceManager->SoundManager.StopMusic("finalogg.ogg");
			//App->Match3Controller.Match3Field->StopAnimateChip(4,1);
			//App->Match3Controller.Match3Field->HighlightMatch3();
		}

	}
};





//What to do on init
void TMyApplication::InnerInit()
{
	#ifdef TARGET_ANDROID
	SE::ST::PathToResources = "";
	#endif
	#ifdef TARGET_WIN32
		#ifdef DEBUG
	SE::ST::PathToResources = "../../assets/";
		#else
	SE::ST::PathToResources = "res/";
		#endif
	#endif
	#ifdef TARGET_IOS
	SE::ST::PathToResources = "assets/";
	#endif

	if (SE::Console != nullptr) {
		*SE::Console << "APP INIT\n";
	}
	
	SE::ResourceManager->ShaderManager.AddShader("DefaultShader", "shader1vertex.txt", "shader1fragment.txt");
	SE::ResourceManager->ShaderManager.AddShader("FrameShader", "frameshader_vertex.txt", "frameshader_fragment.txt");
	SE::ResourceManager->ShaderManager.AddShader("BrickShader", "brickshader_vertex.txt", "brickshader_fragment.txt");
	SE::Renderer->PushShader("DefaultShader");

	const std::string CONST_LOADING_BACKGROUND_BLACK = "loading_background_black";
	const std::string CONST_LOADING_TEXTURE = "loading";
	const std::string CONST_LOGO_SMALL_TEXTURE = "logo_small";

	SE::ResourceManager->TexList.AddTexture(CONST_LOADING_BACKGROUND_BLACK + ".png", CONST_LOADING_BACKGROUND_BLACK);
	SE::ResourceManager->TexList.AddTexture(CONST_LOADING_TEXTURE + ".png", CONST_LOADING_TEXTURE);
	SE::ResourceManager->TexList.AddTexture(CONST_LOGO_SMALL_TEXTURE + ".png", CONST_LOGO_SMALL_TEXTURE);

	SE::ResourceManager->TexList.AddTexture("console_bkg.bmp");

	SE::ResourceManager->FrameManager.AddFrameRenderBuffer("LevelBuffer", 512, 512);

	Inited = true;

	SE::Renderer->SetOrthoProjection();

	SE::Renderer->SetFullScreenViewport();


	auto px = SE::FileToPropertyTree("shaders.xml");
	SE::ResourceManager->ShaderManager.Serialize(*px);

	px = SE::FileToPropertyTree("textures.xml");
	SE::ResourceManager->TexList.Serialize(*px);



	//test
	SE::ResourceManager->TexList.AddTexture("levelshot1.png");

	testPair.second.Data.Vec3CoordArr[SE::CONST_STRING_POSITION_ATTRIB].emplace_back(Eigen::Vector3f(-100, -100, 0));
	testPair.second.Data.Vec3CoordArr[SE::CONST_STRING_POSITION_ATTRIB].emplace_back(Eigen::Vector3f(100, 0, 0));
	testPair.second.Data.Vec3CoordArr[SE::CONST_STRING_POSITION_ATTRIB].emplace_back(Eigen::Vector3f(0, 100, 0));

	testPair.second.Data.Vec2CoordArr[SE::CONST_STRING_TEXCOORD_ATTRIB].emplace_back(Eigen::Vector2f(0, 0));
	testPair.second.Data.Vec2CoordArr[SE::CONST_STRING_TEXCOORD_ATTRIB].emplace_back(Eigen::Vector2f(1, 0));
	testPair.second.Data.Vec2CoordArr[SE::CONST_STRING_TEXCOORD_ATTRIB].emplace_back(Eigen::Vector2f(0, 1));

	testPair.first.ShaderName = "DefaultShader";

	testPair.first.SamplerMap[SE::CONST_STRING_TEXTURE_UNIFORM] = "levelshot1.png";
	testPair.second.RefreshBuffer();
	//end


	//this cause exception
	//px = SE::FileToPropertyTree("fonts.xml");
	//SE::ResourceManager->FontManager.Serialize(*px);
	//SE::ResourceManager->FontManager.PushFont("droid_sans14");


	/*
	
	ResourceManager->GUIManager.AddWidgetAndFill(boost::shared_ptr<TInstancingWidgetAncestor>(new TSquareButton),
		"ololo", "group1", 
		boost::shared_ptr<TTriangleListFillerAncestor>(new TSquareButtonTriangleListFiller(vec2(100, 100), vec2(200, 200), "button_normal", "button_pressed")));
		

	ResourceManager->GUIManager.AddWidgetAndFill(boost::shared_ptr<TInstancingWidgetAncestor>(new TSquareStatic),
		"Background", "group1", 
		boost::shared_ptr<TSquareStaticTriangleListFiller>(new TSquareStaticTriangleListFiller(vec2(0, 0), vec2(800, 480), "cave_hd")));
		
	
	ResourceManager->GUIManager.AddWidget(boost::shared_ptr<TInstancingWidgetAncestor>(new TMatch3Field(Match3Controller)),
		"match3", "group1");

	ResourceManager->GUIManager.MoveWidget("ololo", vec2(-100, 0));

	TOnClickTest OnClickTest;
	*/


	//ResourceManager->GUIManager.GetOnClickSignal("ololo").connect(OnClickTest);

	//testAnimObject.Serialize(FileToPropertyTree("test_animation_xml.xml"));
	
	//ResourceManager->HalibutAnimationManager.AddAnimationObject("test_anim", testAnimObject);

	//ResourceManager->HalibutAnimationManager.StartAnimation("test_anim");


	//ResourceManager->ShaderManager.AddShader("DefaultShader", "shader_vertex.txt", "shader_fragment.txt");
	/*HalibutRender->PushShader("DefaultShader");

	ResourceManager->TexList.AddTexture(CONST_CONSOLE_TEX_NAME);

	ResourceManager->FontManager.AddFont("droid_sans14", "droid_sans14_font_bitmap.bmp32", "droid_sans14_font_charmap.txt");
	ResourceManager->FontManager.PushFont("droid_sans14");*/

}

//What to do on deinit
void TMyApplication::InnerDeinit()
{
	Inited = false;
}

//What to do on draw
void TMyApplication::InnerDraw()
{
	using namespace SE;
	Renderer->SetPerspectiveProjection(pi / 6, 10.f, 10000.f);
	Renderer->SetFullScreenViewport();
	Renderer->PushMatrix();
	float phi = pi / 6;
	float alpha = 0;
	float distance = 2000;
	Renderer->TranslateMatrix(Vector3f(0, 0, -distance));	
	Vector4f quat1 = Vector4f(sin(phi / 2), 0, 0, cos(phi / 2));
	Vector4f quat2 = Vector4f(0, sin(alpha / 2), 0, cos(alpha / 2));
	Renderer->RotateMatrix(quat1);
	Renderer->RotateMatrix(quat2);
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);
	CheckGlError("");
	auto mat1 = quatToMatrix(quat1);
	auto mat2 = quatToMatrix(quat2);
	Vector3f lightPos = { 0.f, 1.f, 1.f };
	Vector3f eye = mat2 * mat1 * Vector3f(0.0f, 0.f, -distance);
	{
		TRenderParamsSetter params(testPair.first);
		RenderUniform3fv("eye", eye.data());
		RenderUniform3fv("lightPos", lightPos.data());
		Matrix3f normMatrix = Renderer->GetModelviewMatrix().inverse().transpose().block<3, 3>(0, 0);
		RenderUniformMatrix3fv("NormalMatrix", false, normMatrix.data());
		RenderUniformMatrix4fv("ModelViewMatrix", false, Renderer->GetModelviewMatrix().data());
		RenderUniformMatrix3fv("ModelViewMatrix3x3", false, Renderer->GetModelviewMatrix().block<3, 3>(0, 0).data());
		Renderer->DrawTriangleList(testPair.second);
	}
	Renderer->PopMatrix();
	CheckGlError("");

}

//What to do on update. timer means how many ms passed since last update
void TMyApplication::InnerUpdate(size_t timer)
{
}
