#include "VCamera.h"
#include <GL/glew.h>
#include <GL/glut.h>
#include "vmath.h"
#include <math.h>
#include <iostream>

using namespace std;

VCamera::VCamera(int * width, int * height, float distance)
{
    this->winwidth = width;
    this->winheight = height;
	this->angleX = 0.0f;
	this->angleY = 0.0f;
	this->maxdistance = 8.0f;
	this->mindistance = 2.0f;
	this->setDistance(distance);
	this->deleteFromPoint();
}

VCamera::~VCamera()
{
    
}

void VCamera::setCamera()
{
	//cout << "set camera" << endl;
	//glTranslatef(0,0,this->distance);
	glTranslatef(0,0,-this->distance);
	glRotatef(-this->angleX, 1.0f, 0.0f, 0.0f );
	glRotatef(-this->angleY, 0.0f, 1.0f, 0.0f );
}

void VCamera::setRotation() {
	glRotatef(this->angleX, 1.0f, 0.0f, 0.0f );
	glRotatef(-this->angleY, 0.0f, 1.0f, 0.0f );
}

float VCamera::getDistance ()
{
	return this->distance;
}

void VCamera::setAxisAlign(int axis) {
	switch(axis) {
		case 0: this->angleX = 0.0f; this->angleY = -90.0f; break; //x
		case 1: this->angleX = 90.0f; this->angleY = 0.0f; break; //y
		case 2: this->angleX = 0.0f; this->angleY = 0.0f; break; //z
	}
}

void VCamera::setDistance (float cameraDistance)
{
	if(cameraDistance <= this->maxdistance && cameraDistance >= this->mindistance) {
		this->distance = cameraDistance;
	}
}

void VCamera::setFromPoint(int x,int y) {
	//cout << x << " " << y;
	this->fromPoint[0] = x;
	this->fromPoint[1] = y;
}

void VCamera::deleteFromPoint() {
	this->fromPoint[0] = 0;
	this->fromPoint[1] = 0;
}

void VCamera::changeDirection(int x, int y)
{
	//cout << "changing direction" << endl;
	//cout << this->fromPoint[0] << " " << this->fromPoint[1] << endl;
    Vector2<float> toPoint(x,y);
	Vector2<float> diffPoint = toPoint - fromPoint;

	this->angleX += -(diffPoint[1]/ (*winheight) * 180);
	this->angleY += -(diffPoint[0]/ (*winwidth) * 180);

	fromPoint = toPoint;
}

void VCamera::changeDistance(int x, int y)
{
    Vector2<float> toPoint(x,y);
	Vector2<float> diffPoint = toPoint - fromPoint;

	float maxlength = sqrt((float)(*winwidth)*(*winwidth)+(*winheight)*(*winheight));
	float newdistance = (diffPoint.length()/maxlength)*this->maxdistance;

	float sum = diffPoint[0] + diffPoint[1];
	if(sum >= 0) {
		this->setDistance(this->distance + newdistance);
	} else {
		this->setDistance(this->distance - newdistance);
	}
	//cout << diffPoint[0] << " " << diffPoint[1] << endl;

	fromPoint = toPoint;
}