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

using namespace std;

VSlider::VSlider(float initialvalue, int x1, int y1, int x2, int y2, float * alph)
{
	this->value = initialvalue;
	this->begin = Vector2<float>(x1,y1);
	this->end = Vector2<float>(x2,y2);
	this->offset = 10;
	this->alpha = alph;
	this->color = Vector3<float>(1.0,0.0,0.0);
}

VSlider::~VSlider(void){
}

void VSlider::render() {
	//draw line
	glLineWidth(2);
	glEnable(GL_LINE_SMOOTH);
	glBegin(GL_LINES);
		glColor4f(this->color.x,this->color.y,this->color.z,*this->alpha);
		glVertex2i(this->begin.x, this->begin.y);
		glVertex2i(this->end.x, this->end.y);
	glEnd();
	//draw slide element
	Vector2<float> pos = this->begin.lerp(this->value,this->end);
	glLineWidth(7);
	glBegin(GL_LINES);
		glColor4f(this->color.x,this->color.y,this->color.z,*this->alpha);
		glVertex2i(pos.x-this->offset,pos.y);
		glVertex2i(pos.x+this->offset,pos.y);
	glEnd();
	glLineWidth(1);
	glDisable(GL_LINE_SMOOTH);
	//draw text
	glColor4f(1.0,1.0,1.0,*this->alpha);
	char prozent[20];
	char * ch;
	_snprintf_s(prozent, 20, "%.2f", this->value);
	glRasterPos3f(pos.x-this->offset-27, pos.y+3, 0.0);
	for(ch = prozent; *ch; ch++) {
		glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, (int)*ch);
	}
}

bool VSlider::isInside(int xm,int ym) {
	Vector2<float> pos = this->begin.lerp(this->value,this->end);
	Vector2<float> mouse(xm,ym);
	return (pos-mouse).length() < this->offset;
}

float * VSlider::getValue() {
	return &this->value;
}

void VSlider::pressed(int xm,int ym) {
	this->fromPoint.x = xm;
	this->fromPoint.y = ym;
}

void VSlider::drag(int xm,int ym) {
	Vector2<float> toPoint(xm,ym);
	Vector2<float> diffPoint = toPoint - fromPoint;

	float maxlength = (this->begin-this->end).length();
	float newvalue = (diffPoint.length()/maxlength);

	float sum = diffPoint[0] + diffPoint[1];
	if(sum >= 0) {
		if(this->value-newvalue >= 0.0)
			this->value -= newvalue;
	} else {
		if(this->value+newvalue <= 1.0)
			this->value += newvalue;
	}

	fromPoint = toPoint;
}

void VSlider::setValue(float val) {
	if(val >= 0.0 && val <= 1.0)
		this->value = val;
}

void VSlider::released(int xm,int ym) {
	this->fromPoint.x = 0;
	this->fromPoint.y = 0;
}