#include "Camera.h"

#include <glew.h>
#include <GL/glut.h >

Camera::Camera()
{
	distance = 50;

	angleX = 15.0 * 3.1415 / 180.0;
	angleY = 0;
	updateTransform();

	position = Vector(0, 0, 1);
	position.Normalize();

	lookAt.x = 0;
	lookAt.y = 5;
	lookAt.z = 0;

	up = Vector(0, 1, 0);
}

void Camera::increaseDistance()
{
	if( distance + 0.5 > DISTANCE_MAX )
		distance = DISTANCE_MAX;
	else
		distance += 0.5;
}

void Camera::decreaseDistance()
{
	if( distance - 0.5 < DISTANCE_MIN )
		distance = DISTANCE_MIN;
	else
		distance -= 0.5;
}

void Camera::render()
{
	Vector newPos = position * distance;
	Vector transformedPos(
		transform.mCell[0]*newPos.x + transform.mCell[4]*newPos.y + transform.mCell[8]*newPos.z + transform.mCell[12],
		transform.mCell[1]*newPos.x + transform.mCell[5]*newPos.y + transform.mCell[9]*newPos.z + transform.mCell[13],
		transform.mCell[2]*newPos.x + transform.mCell[6]*newPos.y + transform.mCell[10]*newPos.z + transform.mCell[14]);

	Vector eye = lookAt + transformedPos;

	gluLookAt(
			eye.x, eye.y, eye.z,
			lookAt.x, lookAt.y, lookAt.z, 
			up.x, up.y, up.z
		);
}

void Camera::rotateX(float angle)
{
	float a = angleX + angle;
	if( a < 3.1415/2.0 && a > -3.1415/2.0 )
	{
		angleX += angle;
		updateTransform();
	}
}

void Camera::rotateY(float angle)
{
	angleY += angle;
	updateTransform();
}

void Camera::updateTransform()
{
	OSkA::Matrix matx, maty;
	matx.SetRotateX(-angleX);
	maty.SetRotateY(-angleY);

	transform = maty * matx;
}