#include "VAxisAlignElement.h"
#include <iostream>
#include "V2Ddraw.h"
#include "corona.h"
#include "VCamera.h"
#include <GL/glew.h>
#include <GL/glut.h>
#include <math.h>

using namespace std;

VAxisAlignElement::VAxisAlignElement(int* width, int* height, unsigned int* fps, VCamera * cam):
	GUIelement(width,height,fps)
{
	this->offset = 40;
	this->x = offset+20; //(int)*(this->wwidth)*0.02;
	this->y = (int)*(this->wheight)-(offset+20); //*0.75;
	this->active = true;
	this->camera = cam;
	this->dragging = false;
}

VAxisAlignElement::~VAxisAlignElement(void)
{

}

void VAxisAlignElement::render() {
	glLineWidth(4);
	glEnable(GL_LINE_SMOOTH);
	glPushMatrix();
	
	glTranslatef(this->x,this->y,0.0f);
	
	camera->setRotation();

	glBegin(GL_LINES);
	//x
	glColor4f(1,0,0,1);
	glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line
	glVertex3f(offset, 0.0f, 0.0f); // end point of the line

	//y
	glColor4f(0,1,0,1);
	glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line
	glVertex3f(0.0f, -offset, 0.0f); // end point of the line

	//z
	glColor4f(0,0,1,1);
	glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line
	glVertex3f(0.0f, 0.0f, offset); // end point of the line

	glEnd( );
	glPopMatrix();
	glDisable(GL_LINE_SMOOTH);
	glLineWidth(1);
}

void VAxisAlignElement::released(int x, int y) {
	if(!this->dragging) { //click
		//cout << "click" << endl;
		float pixels[3];
		GLint viewport[4];
		glGetIntegerv(GL_VIEWPORT,viewport);
		glReadPixels(x,viewport[3]-y,1,1,GL_RGB,GL_FLOAT,pixels);
		if(pixels[0] == 1.0 && pixels[1] == 0.0 && pixels[2] == 0.0) {
			//cout << "red" << endl;
			this->camera->setAxisAlign(0);
		} else if(pixels[0] == 0.0 && pixels[1] == 1.0 && pixels[2] == 0.0) {
			//cout << "green" << endl;
			this->camera->setAxisAlign(1);
		} else if(pixels[0] == 0.0 && pixels[1] == 0.0 && pixels[2] == 1.0) {
			//cout << "blue" << endl;
			this->camera->setAxisAlign(2);
		}
	}
	this->dragging = false;
}

void VAxisAlignElement::drag(int,int) {
	this->dragging = true;
}

bool VAxisAlignElement::isInside(int xm, int ym) {
	return sqrt(pow((double)ym-this->y,2)+pow((double)xm-this->x,2)) < this->offset;
}