
#include <iostream>
#include <fstream>

#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 <Camera.h>
#include <Player.h>

#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>

#include "ResourceManager.h"
#include "PointLight.h"

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow* window);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);

int SCR_WIDTH = 1600;
int SCR_HEIGHT = 900;

//Camera camera(glm::vec3(20.0f, 1.0f, 20.0f));
glm::vec3 StartingPosition = glm::vec3(20.0f, 0.0f, 20.0f);
glm::vec3 StartingRotation = glm::vec3(0.0f, 0.0f, 0.0f);
Player PlayerCharacter(StartingPosition, StartingRotation);

float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;

float deltaTime = 0.0f;
float lastFrame = 0.0f;
float elapsedTime = 0.0f;

int amountOfCubes = 1000;

//glm::vec3 lightPos(1.2f, 1.0f, 2.0f);

int main() 
{
	const char* glsl_version = "#version 330";
	std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearningOpenGl", NULL, NULL);
	if (window == NULL) {
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}

	glfwMakeContextCurrent(window);
	glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
	glfwSetCursorPosCallback(window, mouse_callback);
	glfwSetScrollCallback(window, scroll_callback);

	//glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
		std::cout << "Failed to initialize GLAD" << std::endl;
		return -1;
	}

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

	std::cout << "Loaded GLFW context, OpenGL 3.3" << std::endl;

	IMGUI_CHECKVERSION();
	ImGui::CreateContext();
	ImGuiIO& io = ImGui::GetIO();
	io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
	io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
	io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;

	//ImGui_ImplGlfw_InitForOpenGL(window, true);
	//ImGui_ImplOpenGL3_Init(glsl_version);

	if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) {
		std::cout << "Failed to initialize ImGui GLFW backend" << std::endl;
	}
	if (!ImGui_ImplOpenGL3_Init(glsl_version)) {
		std::cout << "Failed to initialize ImGui OpenGL backend" << std::endl;
	}

	Shader simple_depth_shader = ResourceManager::LoadShader("point_shadow_depth.vert", "point_shadow_depth.frag", "point_shadow_depth.geom", "simple_depth_shader");

	Shader wall_shader = ResourceManager::LoadShader("wall_test.vert", "wall_test.frag", nullptr, "wall");

	LevelMap level_map = ResourceManager::LoadLevelMap("map_test.txt", "test_level");

	level_map.RenderSetup(&wall_shader, &wall_shader, &wall_shader);

	int number_of_point_lights = 0;

	std::vector<PointLight> point_lights_vector;
	
	//PointLight point_light3(glm::vec3(30.0f, 3.0f, 30.0f), glm::vec3(1.0f, 1.0f, 1.0f), simple_depth_shader);

	//PointLight point_light2(glm::vec3(70.0f, 2.0f, 55.0f), glm::vec3(1.0f, 1.0f, 1.0f), simple_depth_shader);

	//PointLight point_light(glm::vec3(20.0f, 3.0f, 35.0f), glm::vec3(1.0f, 1.0f, 1.0f), simple_depth_shader);

	//PointLight point_lights[3] = { point_light, point_light2, point_light3 };

	/*unsigned int depthCubemap, depthMapFBO;

	glGenFramebuffers(1, &depthMapFBO);
	glGenTextures(1, &depthCubemap);

	glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);

	for (unsigned int i = 0; i < 6; ++i)
	{
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
	}
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

	glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
	glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthCubemap, 0);
	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);
	glBindFramebuffer(GL_FRAMEBUFFER, 0);*/
	
	float r = 0.05f, g = 0.05f, b = 0.05f;

	while (!glfwWindowShouldClose(window)) {
		//timing
		float currentFrame = (float)glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		elapsedTime += deltaTime;

		//input
		processInput(window);

		ImGui_ImplOpenGL3_NewFrame();
		ImGui_ImplGlfw_NewFrame();
		ImGui::NewFrame();

		ImGui::Begin("Settings");
		ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
		if (ImGui::Button("Create Light") && number_of_point_lights < 10) {
			point_lights_vector.push_back(PointLight(PlayerCharacter.Position, glm::vec3(1.0f, 1.0f, 1.0f), simple_depth_shader));
			number_of_point_lights = point_lights_vector.size();
		}
		//ImGui::SliderInt("Amount of cubes: ", &amountOfCubes, 0, 1000);
		ImGui::End();

		ImGui::Render();

		// view/projection transformations

		glClearColor(r, g, b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		//glDisable(GL_CULL_FACE);

		//level_map.GetMeshes();

		for (PointLight& point_light : point_lights_vector)
		{
			point_light.RenderSceneShadows(level_map.GetMeshes());
		}

		//for (int i = 0; i < numOfPointLights; i++)
		//{
		//	point_lights[i].RenderSceneShadows(level_map.GetMeshes());
		//}

		glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		wall_shader.Use();
		// CHANGED PROJECTION TO USE FLAT 45 TO GET PLAYER CHARACTER TO WORK
		glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
		glm::mat4 view = PlayerCharacter.GetViewMatrix();
		wall_shader.SetMatrix4("projection", projection);
		wall_shader.SetMatrix4("view", view);
		wall_shader.SetVector3f("viewPosition", PlayerCharacter.Position);

		wall_shader.SetVector3f("material.ambientColor", glm::vec3(1.0f, 0.0f, 0.0f));
		wall_shader.SetVector3f("material.diffuseColor", glm::vec3(0.5f, 0.5f, 0.5f));
		wall_shader.SetVector3f("material.specularColor", glm::vec3(0.0f, 0.0f, 1.0f));
		wall_shader.SetFloat("material.shininess", 1.0f);
		// set lighting uniforms
		wall_shader.SetInteger("numOfPointLights", number_of_point_lights);
		int light_index = 0;
		for (PointLight& point_light : point_lights_vector)
		{
			std::string name = "pointLights[" + std::to_string(light_index) + "].";
			wall_shader.SetVector3f((name + "base.color").c_str(), point_light.color);
			wall_shader.SetFloat((name + "base.ambientIntensity").c_str(), point_light.ambient_intensity);
			wall_shader.SetFloat((name + "base.diffuseIntensity").c_str(), point_light.diffuse_intensity);
			wall_shader.SetFloat((name + "atten.constant").c_str(), point_light.attenuation_constant);
			wall_shader.SetFloat((name + "atten.linear").c_str(), point_light.attenuation_linear);
			wall_shader.SetFloat((name + "atten.exponential").c_str(), point_light.attenuation_exponential);
			wall_shader.SetVector3f((name + "position").c_str(), point_light.Position);
			wall_shader.SetFloat((name + "farPlane").c_str(), point_light.far_plane);
			wall_shader.SetInteger((name + "depthMap").c_str(), light_index);
			glActiveTexture(GL_TEXTURE0 + light_index);
			glBindTexture(GL_TEXTURE_CUBE_MAP, point_light.depth_map);

			light_index++;
		}
		/*wall_shader.SetVector3f("pointLights[0].base.color", point_light.color);
		wall_shader.SetVector3f("pointLights[0].base.ambientIntensity", point_light.ambient);
		wall_shader.SetVector3f("pointLights[0].position", point_light.position);
		wall_shader.SetVector3f("lightPosition2", point_light2.position);
		wall_shader.SetVector3f("lightColor", point_light.color);*/
		//wall_shader.SetInteger("shadows", 1); // enable/disable shadows by pressing 'SPACE'
		//wall_shader.SetInteger("depthMap", 0);


		GLenum err;
		while(err = glGetError())
		{
			std::cout << "Error: " << err << std::endl;
		}

		for (auto* mesh : level_map.GetMeshes()) 
		{
		//	//std::cout << "Rendering mesh" << std::endl;
			mesh->Render(wall_shader);
		}


		/*float near_plane = 1.0f;
		float far_plane = 50.0f;
		glm::mat4 shadowProj = glm::perspective(glm::radians(90.0f), (float)SHADOW_WIDTH / (float)SHADOW_HEIGHT, near_plane, far_plane);*/
		/*std::vector<glm::mat4> shadowTransforms;
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
		shadowTransforms.push_back(shadowProj * glm::lookAt(lightPos, lightPos + glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)));*/

		/*glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
		glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
		glClear(GL_DEPTH_BUFFER_BIT);
		glCullFace(GL_FRONT);
		simpleDepthShader.Use();
		for (unsigned int i = 0; i < 6; ++i)
			simpleDepthShader.SetMatrix4("shadowMatrices[" + std::to_string(i) + "]", shadowTransforms[i]);
		simpleDepthShader.SetFloat("far_plane", far_plane);
		simpleDepthShader.SetVector3f("lightPos", lightPos);
		levelMap.Update(projection, view);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glCullFace(GL_BACK);

		glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubemap);*/
		//map.render(projection, view, lightPos, deltaTime, glm::vec3(SCR_WIDTH, SCR_HEIGHT, 0.0f), far_plane);

		//level_map.Update(projection, view, point_light.position, point_light.color, camera.Position);

		//cubeFactory.render(view, projection, lightPos, deltaTime, amountOfCubes);

		ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
		//check and call
		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	// Cleanup
	ImGui_ImplOpenGL3_Shutdown();
	ImGui_ImplGlfw_Shutdown();
	ImGui::DestroyContext();
	glfwDestroyWindow(window);
	glfwTerminate();
}

void framebuffer_size_callback(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);
	}

	const float cameraSpeed = 5.0f * deltaTime;
	if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) 
		PlayerCharacter.ProcessKeyboard(FORWARD, deltaTime);
	if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
		PlayerCharacter.ProcessKeyboard(BACKWARD, deltaTime);
	if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
		PlayerCharacter.ProcessKeyboard(LEFT, deltaTime);
	if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
		PlayerCharacter.ProcessKeyboard(RIGHT, deltaTime);
}

void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
{
	if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) != GLFW_PRESS) 
	{
		glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
		firstMouse = true;
		return;
	}

	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
		//std::cout << "Mouse callback" << std::endl;
	float xpos = static_cast<float>(xposIn);
	float ypos = static_cast<float>(yposIn);

	if (firstMouse)
	{
		lastX = xpos;
		lastY = ypos;
		firstMouse = false;
	}

	float xoffset = xpos - lastX;
	float yoffset = lastY - ypos;

	lastX = xpos;
	lastY = ypos;

	PlayerCharacter.ProcessMouseMovement(xoffset, yoffset);
}

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
	//PlayerCharacter.ProcessMouseScroll(static_cast<float>(yoffset));
}
