#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <fstream>
#include <string>

#include "shaders/Shader.h"
#include "textures/Texture2D.h"
#include "util/stb_image.h"
#include "util/camera/camera.h"
#include "object/game_object.h"

#include "vertices.h"

// Continue: https://learnopengl.com/Lighting/Multiple-lights
// Chapter: Putting it all together
//
// TODO: look at project->properties->VC++ Directories-> change everything to the Environment var
// For the "real" Nebulix Engine setup everything so it can be compiled/used with VSCode/CLion and not just VS 
// (so basically having an "external" folder which has open gl, GLAD, GLM, stb_image etc. in it or something like this)

// 
// HOW TO redirect error output to file
// Maybe it is possible to redirect to another stream object which adds infos like thread id/time etc.?
// 
// std::ofstream errorFile("error.log");
// std::streambuf* originalCerrBuffer = std::cerr.rdbuf();  // Save original buffer
// Redirect cerr to the error file
// std::cerr.rdbuf(errorFile.rdbuf());

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
typedef glm::mat4 mat4;
typedef glm::vec3 vec3;

Camera cam(glm::vec3(0.0f, 0.0f, 3.0f));

float deltaTime = 0.0f, lastFrameTime = 0.0f;
float mouseLastX = WINDOW_WIDTH / 2, mouseLastY = WINDOW_HEIGHT / 2;

bool firstMouseMove = true;

void OnWindowResize(GLFWwindow* window, int width, int height)
{
	glViewport(0, 0, width, height);
}

void ProcessInput(GLFWwindow* window)
{
	if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
		glfwSetWindowShouldClose(window, true);

	if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
		cam.ProcessKeyboard(MovementDirection::FORWARD, deltaTime);
	if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
		cam.ProcessKeyboard(MovementDirection::BACKWARD, deltaTime);
	if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
		cam.ProcessKeyboard(MovementDirection::LEFT, deltaTime);
	if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
		cam.ProcessKeyboard(MovementDirection::RIGHT, deltaTime);
	if(glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
		cam.ProcessKeyboard(MovementDirection::UP, deltaTime);
	if(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS
		|| glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS)
		cam.ProcessKeyboard(MovementDirection::DOWN, deltaTime);
}

void OnMouseMove(GLFWwindow* window, double xpos, double ypos)
{
	if (firstMouseMove)
	{
		firstMouseMove = false;
		mouseLastX = xpos;
		mouseLastY = ypos;
		return;
	}

	float xoffset = xpos - mouseLastX;
	float yoffset = mouseLastY - ypos; // reversed since y-coordinates range from bottom to top
	mouseLastX = xpos;
	mouseLastY = ypos;

	cam.ProcessMouseMovement(xoffset, yoffset, true);
}

void OnScroll(GLFWwindow* window, double xoffset, double yoffset)
{
	cam.ProcessMouseScroll(yoffset);
}

void Configure(GLFWwindow *window)
{
	OnWindowResize(window, WINDOW_WIDTH, WINDOW_HEIGHT);
	glfwSetFramebufferSizeCallback(window, OnWindowResize);
	glfwSetCursorPosCallback(window, OnMouseMove);
	glfwSetScrollCallback(window, OnScroll);

	stbi_set_flip_vertically_on_load(true); // because an image has 0 at top of y axis and opengl expects it to be on the botton, so if this is omitted, the image will be flipped
	glEnable(GL_DEPTH_TEST);
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}

int main()
{
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Henlo worl", nullptr, nullptr);

	if (window == nullptr)
	{
		std::cerr << "ERROR::GLFW::CREATE_WINDOW";
		glfwTerminate();

		return -1;
	}

	glfwMakeContextCurrent(window);

	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
	{
		std::cerr << "ERROR::GLAD::INITIALISE";
		return -1;
	}	

	Configure(window);

	GLuint faces[]{
		0, 1, 3,
		1, 2, 3
	};
	vec3 cubePositions[] = {
		vec3(0.0f,  0.0f,  0.0f),
		vec3(2.0f,  5.0f, -15.0f),
		vec3(-1.5f, -2.2f, -2.5f),
		vec3(-3.8f, -2.0f, -12.3f),
		vec3(2.4f, -0.4f, -3.5f),
		vec3(-1.7f,  3.0f, -7.5f),
		vec3(1.3f, -2.0f, -2.5f),
		vec3(1.5f,  2.0f, -2.5f),
		vec3(1.5f,  0.2f, -1.5f),
		vec3(-1.3f,  1.0f, -1.5f)
	};


	std::string lightingVertexPath = "shaders/default/default.vert", lampVertexPath = "shaders/default/simple.vert";
	std::string lightingFragmentPath = "shaders/default/default.frag", lampFragmentPath = "shaders/default/simple.frag";

	std::shared_ptr<Nebulix::Shader> lighting, lamp;
	std::vector<std::shared_ptr<Nebulix::Shader>> allShaders = std::vector<std::shared_ptr<Nebulix::Shader>>();
	try
	{
		lighting = std::make_shared<Nebulix::Shader>(lightingVertexPath, lightingFragmentPath);
		lamp = std::make_shared<Nebulix::Shader>(lampVertexPath, lampFragmentPath);
		allShaders.push_back(lighting);
		allShaders.push_back(lamp);
	}
	catch (const std::exception &e)
	{
		std::cerr << e.what();
		return -1;
	}
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	
	Texture2D diffuseMap("images/container2.png", GL_RGBA);
	Texture2D specularMap("images/container2_specular.png", GL_RGBA);

	std::vector<float> objVerts(std::begin(vertices_cube_normals), std::end(vertices_cube_normals));
	std::vector<float> lightVerts(std::begin(vertices_cube_normals), std::end(vertices_cube_normals));
	std::vector<Nebulix::VertexAttribute> objVertexAttribs = { Nebulix::VertexAttribute(), Nebulix::VertexAttribute(), Nebulix::VertexAttribute(2) };
	std::vector<Nebulix::VertexAttribute> lightVertexAttribs = { Nebulix::VertexAttribute()};
	Nebulix::GameObject cube(objVerts, objVertexAttribs);
	vec3 lightPosition = glm::vec3(1.2f, 1.0f, 2.0f);
	Nebulix::GameObject lightBulb(lightVerts, objVertexAttribs, lightPosition, glm::vec3(0.2f));

	std::vector<Nebulix::GameObject> allObjects = std::vector<Nebulix::GameObject>();
	allObjects.push_back(cube);
	allObjects.push_back(lightBulb);

	// main loop
	while(!glfwWindowShouldClose(window))
	{
		float currentFrameTime = (float)glfwGetTime();
		deltaTime = currentFrameTime - lastFrameTime;
		lastFrameTime = currentFrameTime;

		glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		ProcessInput(window);

		mat4 projectionMatrix = glm::perspective(glm::radians(cam.Fov), 800.0f / 600.0f, 0.1f, 100.0f);

		for (size_t i = 0; i < allShaders.size(); i++)
		{
			auto shader = allShaders[i];
			glm::mat4 model = allObjects[i].GetModelMatrix();


			shader->Use();
			shader->SetMatrix("viewMatrix", cam.GetViewMatrix()); // more or less the camera
			shader->SetMatrix("projectionMatrix", projectionMatrix);
			//shader->SetMatrix("modelMatrix", allObjects[i].GetModelMatrix());
			shader->SetMatrix("modelMatrix", model);
		}

		glm::vec3 lightColour;
		lightColour.x = sin(glfwGetTime() * 2.0f);
		lightColour.y = sin(glfwGetTime() * 0.7f);
		lightColour.z = sin(glfwGetTime() * 1.3f);

		glm::vec3 diffuseColour = glm::vec3(1.0f);//lightColour * glm::vec3(0.5f);
		glm::vec3 ambientColour = diffuseColour * glm::vec3(0.1f);

		lighting->Use();
		lighting->SetInt("material.diffuseMap", 0);
		lighting->SetInt("material.specularMap", 1);
		lighting->SetFloat("material.specularColour", 0.5f, 0.5f, 0.5f);
		lighting->SetFloat("material.shininess", 32.0f);
		lighting->SetFloat("spotLight.ambientIntensity", ambientColour);
		lighting->SetFloat("spotLight.diffuseIntensity", diffuseColour);
		lighting->SetFloat("spotLight.specularIntensity", 1.0f, 1.0f, 1.0f);
		lighting->SetFloat("spotLight.position", cam.Position);
		lighting->SetFloat("spotLight.direction", cam.Front);
		lighting->SetFloat("spotLight.cutOffAngle", glm::cos(glm::radians(12.5f)));
		lighting->SetFloat("spotLight.outerCutOffAngle", glm::cos(glm::radians(20.0f)));
		lighting->SetFloat("viewPosition", cam.Position);
		lighting->SetFloat("spotLight.constant", 1.0f);
		lighting->SetFloat("spotLight.linear", 0.09f);
		lighting->SetFloat("spotLight.quadratic", 0.032f);

		diffuseMap.BindTexture();
		diffuseMap.BindTexture(GL_TEXTURE1);

		for (size_t i = 0; i < allObjects.size(); i++)
		{
			allShaders[i]->Use();

			if (i == 0)
			{
				for (size_t j = 0; j < 10; j++)
				{
					allObjects[i].Position = cubePositions[j];
					glm::mat4 model = allObjects[i].GetModelMatrix();
					float angle = 20.0f * j;// * currentFrameTime;
					model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
					
					allShaders[i]->SetMatrix("modelMatrix", model);
					allObjects[i].Draw();
				}
			}
			else
			{
				allObjects[i].Draw();
			}
		}

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;
}