#include "cParticleManager.h"
#include "OGLPlatformSpecific.h"
#include "cGrid.h"
#include "cGame.h"

cParticleManager* cParticleManager::instance_ = 0;

cParticleManager* cParticleManager::instance()
{
    if(instance_ == 0)
        instance_ = new cParticleManager;
    return instance_;
}

cParticleManager::cParticleManager()
{

}

cParticleManager::~cParticleManager()
{
	list<cParticle*>::iterator i;
    for(i = particles_.begin(); i != particles_.end(); ++i)
        delete (*i);
}


void cParticleManager::addParticle(float x, float y, float vx, float vy, float r, float g, float b)
{
	cParticle* p = new cParticle();
	p->x_ = x;
	p->y_ = y;
	p->vx_ = vx;
	p->vy_ = vy;
	p->r_ = r;
	p->g_ = g;
	p->b_ = b;
	p->age_ = 0;
	particles_.push_back(p);
}

list<cParticle*>::iterator cParticleManager::removeParticle(list<cParticle*>::iterator& i)
{	
	cParticle* p = *i;
    list<cParticle*>::iterator newI = particles_.erase(i);
    delete p;
    return newI;
}

void cParticleManager::update(float dt)
{
	list<cParticle*>::iterator i;
    for(i = particles_.begin(); i != particles_.end(); ++i)
	{
		// destroy old particles
		if( (*i)->age_ > 10){ i = removeParticle(i); continue; }
        
		(*i)->age_	+= dt;
		(*i)->x_	+= (*i)->vx_*dt;
		(*i)->y_	+= (*i)->vy_*dt;
		(*i)->vy_	-= .1*dt;
	}
}

void cParticleManager::draw()
{
	float size = .3;
	list<cParticle*>::iterator i;
    for(i = particles_.begin(); i != particles_.end(); ++i)
	{
		 glPushMatrix();

		 glScalef(.25,.25,.25);
		 glTranslatef(((*i)->x_ - cGrid::gridXSize_/2) * 2, ((*i)->y_- cGrid::gridYSize_/2) * 2, 0);
		 glColor3f( (*i)->r_, (*i)->g_, (*i)->b_); 
		

		 glRotatef(cGame::instance()->t_*50 + (*i)->uniqueness_, 0, 1, 0);

		 /*
		 glBegin(GL_POINTS);						
		 glVertex3f(0, 0, 0); 	
		 glEnd();
		 */

		glNormal3f(0,0,1);
		glBegin(GL_TRIANGLES);						
        glVertex3f((*i)->a, (*i)->b, 0); 	
        glVertex3f(-(*i)->c, (*i)->d, 0); 
        glVertex3f((*i)->e, -(*i)->f, 0); 
		glEnd();

		glPopMatrix();
	}
}