#include "SDL.h"
#include "SDL_opengl.h"
#include "energy.h"
#include "util.h"
#include "config.h"

namespace PRJID {
	Energy::Energy(unsigned int m) {
		draw_warn=false;
		max=m;
		label_dl=0;
		reset();
	}

	Energy::~Energy() {
		if (label_dl!=0) { glDeleteLists(label_dl,1); }
	}

	void Energy::reset() {
		current=max;
	}
	bool Energy::empty() {
		if (current>0) return false;
		return true;
	}
	bool Energy::can_afford(unsigned int c) {
		if (current<c) return false;
		return true;
	}

	bool Energy::tick(unsigned int ticks) {
		lastreduce.tick(ticks);
		return empty();
	}

	int Energy::percent() {
		float one=static_cast<float>(max)/100.0f;
		float perc=static_cast <float>(current)/one;

		int r=static_cast<int>(perc);
		if (r<0) r=0;
		if (r>100) r=100;
		return r;
	}
	void Energy::cap() {
		if (current>max) current=max;
	}

	void Energy::set_current(unsigned int c) {
		current=c;
		cap();
	}
	void Energy::gain(unsigned int g) {
		current+=g;
		cap();
	}
	void Energy::reduce(unsigned int g) {
		lastreduce=Timeleft(1000);
		if (g>=current) { 
			current=0;
		} else {
			current-=g;
		}
		cap();
	}
	void Energy::change(int g) {
		if (g>0) gain(g);
		if (g<0) reduce(g*-1);
		cap();
	}

	bool Energy::recent_loss() {
		return !lastreduce.over();
	}

	void Energy::dim(C3 c,C3f s,C3f t) {
		color=c;
		scale=s;
		trans=t;
	}
	void Energy::override_color(C3 c) {
		glColor3ub(c.x,c.y,c.z);
		color_override=true;
	}
	void Energy::warn(bool status) {
		draw_warn=status;
	}

	void Energy::label(std::string l,C3 pos) {
			label_dl=glGenLists(1);
			glNewList(label_dl,GL_COMPILE);
			glColor3ub(250,250,250);
			Font_ogl::write(pos,l);
			glEndList();
	}

	void Energy::draw() {
		if (label_dl!=0) {
			glCallList(label_dl);
		}
		if (draw_warn&&recent_loss()) {
			glColor3ub(250,0,0);
			bar(C3(),C3(Config::dx(),3));
		}
		if (percent()==0) return;
		glPushMatrix();
		glTranslatef(trans.x,trans.y,trans.z);
		glScalef(scale.x,scale.y,scale.z);
		if (!color_override) { glColor3ub(color.x,color.y,color.z); }
		color_override=false;
		bar(
			C3(0,0),
			C3(percent(),1)
		);
		glPopMatrix();




	}


} //namespace
