
#include "SDL_opengl.h"

#include "radio.h"

#include "tweak/tweak.h"

#include "tex.h"

namespace PRJID {

void texquad(GLuint t) {
   glBindTexture(GL_TEXTURE_2D, t);

	glEnable(GL_TEXTURE_2D);
   glBegin(GL_QUADS);

   glTexCoord2f(0,0);
   glVertex2i(0,0);
   glTexCoord2f(0,1);
   glVertex2i(0,1);

   glTexCoord2f(1,1);
   glVertex2i(1,1);
   glTexCoord2f(1,0);
   glVertex2i(1,0);

   glEnd();
	glDisable(GL_TEXTURE_2D);
}


Radio::Radio() {
	seqnum=0;
	current=RT_NONE;
	triggertime=0;
	myticks=0;
}
void Radio::add(RadioEntry e) {
	std::list <RadioEntry>::iterator it;

	unsigned int s=0;
	for (it=entries.begin();it!=entries.end();it++) {
		if ((*it).trigger!=e.trigger) continue;
		if ((*it).seqnum>s) {
			s=(*it).seqnum;
		}
	}
	
	if (e.seqnum==0) e.seqnum=s+1;
	if (e.duration==0) {
		e.duration=Tweak::radio_duration_default_i();
	}
	entries.insert(entries.end(),e);
}

bool Radio::load(std::string path) {

	GLuint texture;
	texture=Tex::load("test.png",path);
	add( RadioEntry(RT_TEST,texture) );

	texture=Tex::load("incoming2.png",path);
	add( RadioEntry(RT_START,texture) );

	texture=Tex::load("nearlydead.png",path);
	add( RadioEntry(RT_NEARLYDEAD,texture) );

	texture=Tex::load("win.png",path);
	add( RadioEntry(RT_WIN,texture) );

	texture=Tex::load("good.png",path);
	add( RadioEntry(RT_GOOD,texture) );

	texture=Tex::load("dead.png",path);
	add( RadioEntry(RT_DEAD,texture) );

	texture=Tex::load("toofar.png",path);
	add( RadioEntry(RT_TOOFAR,texture) );

	TriggerTimer timer;
	timer.trigger=RT_START;
	timer.time=Tweak::radio_timer_start_i();

	timers.insert(timers.end(),timer);

	return true;
}

void Radio::draw() {

	GLuint tex;

	tex=get();
	if (tex==0) return;
	glPushMatrix();

	C3f p=Tweak::radio_pos_C3f();
	glTranslatef( p.x,p.y,p.z );
	C3f s=Tweak::radio_scale_C3f();
	glScalef(s.x,s.y,s.z);
	glColor3f(1,1,1);
	texquad(tex);

	glPopMatrix();
}

void Radio::trigger_once(E_RadioTrigger t) {
	if (had.find(t)!=had.end()) return;
	trigger(t);
	had.insert(t);
}



void Radio::trigger(E_RadioTrigger t) {
	current=t;
	seqnum=1;
	triggertime=0;
}

GLuint Radio::get() {
	if (current==RT_NONE) return 0;
	std::list <RadioEntry>::iterator it;
	for (it=entries.begin();it!=entries.end();it++) {
		if ((*it).trigger!=current) continue;
		if ((*it).seqnum!=seqnum) { continue; }
		if (triggertime>(*it).duration) {
			seqnum++;
			triggertime=0;
		}
		return (*it).texture;
	}
	seqnum=0;
	triggertime=0;
	current=RT_NONE;
	return 0;
}

void Radio::tick(unsigned int ticks) {
	triggertime+=ticks;
	myticks+=ticks;
	std::list <TriggerTimer>::iterator it;

	for (it=timers.begin();it!=timers.end();it++) {
		if ((*it).time==0) continue;
		if (myticks>(*it).time) {
			trigger((*it).trigger);
			(*it).time=0;
			break;
		}
	}
}

Radio *radio_;
Radio *Radio::instance() {
	if (radio_==NULL) {
		radio_=new Radio();
	}
	return radio_;
}
std::ostream& operator<<(std::ostream&s, Radio sk) {
	return s;
}

} //namespace
