#include <render/render_shared.h>
#include <game/camera.h>

Camera g_camera;

struct CameraGlobals {
  int mouseX = 0;
  int mouseY = 0;
  int prevMouseX = 0;
  int prevMouseY = 0;
  int deltaMouseX = 0;
  int deltaMouseY = 0;
} g_cameraGlobals;

void cameraUpdateMouseLook( int x, int y )
{
	CameraGlobals& camg = g_cameraGlobals;
	camg.mouseX = x;
	camg.mouseY = y;
	
	camg.deltaMouseX = camg.mouseX - camg.prevMouseX;
	camg.deltaMouseY = camg.mouseY - camg.prevMouseY;
	
	camg.prevMouseX = camg.mouseX;
	camg.prevMouseY = camg.mouseY;

	g_camera.yaw += (float)camg.deltaMouseX * 0.2f;
	g_camera.pitch -= (float)camg.deltaMouseY * 0.2f;

	//if (g_camera.yaw > 180.0f)
	//	g_camera.yaw -= 180.0f;
	//else if (g_camera.yaw < -180.0f)
	//	g_camera.yaw += 180.0f;

	if (g_camera.pitch > 89.0f)
		g_camera.pitch = 89.0f;
	if (g_camera.pitch < -89.0f)
		g_camera.pitch = -89.0f;
}

void cameraUpdateLook(const Vec3& target, float dist)
{
	float yaw = (float)g_camera.yaw;
	float pitch = (float)g_camera.pitch;

	//yaw *= 0.2f;
	//pitch *= 0.2f;

	glm::vec3 direction = glm::vec3(0.0f);
	direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
	direction.y = sin(glm::radians(pitch));
	direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));

	g_camera.look = glm::vec3(target.x, target.y, target.z);

	g_camera.eye = g_camera.look - direction * dist;

	//g_camera.eye = glm::vec3(eye.x, eye.y, eye.z);
}

void cameraUpdateLook_FPS(const Vec3& pos)
{
	float yaw = (float)g_camera.yaw;
	float pitch = (float)g_camera.pitch;

	glm::vec3 direction = glm::vec3(0.0f);
	direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
	direction.y = sin(glm::radians(pitch));
	direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));

	g_camera.eye = ToGlm(pos);
	g_camera.look = direction;
}

glm::vec3 cameraGetDirection()
{
	float yaw = (float)g_camera.yaw;
	float pitch = (float)g_camera.pitch;

	glm::vec3 direction = glm::vec3(0.0f);
	direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
	direction.y = sin(glm::radians(pitch));
	direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
	return direction;
}

Vec3 cameraGetDir()
{
	return Vec3(ToEngine(cameraGetDirection()));
}

void cameraPushToRender()
{	
	static glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
	g_renderView.view = glm::lookAt(g_camera.eye, g_camera.eye + g_camera.look, up);
}
