#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <stdlib.h>

#include "draw.h"
#include "fireworks.h"
#include "level.h"

struct firework {
	float x, y, z;
	float speed;
	float r, g, b;
	float radius;
};

#define NUM_FIREWORKS 10
#define EXPLODE_HEIGHT 3

static Level *level;
static struct firework fireworks[NUM_FIREWORKS];

static inline float rand_color()
{
	return (rand() % 256) / 256.0;
}

static void init_firework(struct firework *firework)
{
	firework->x = rand() % level->w;
	firework->y = rand() % level->h;
	firework->z = 0;
	firework->speed = 0.3 + (rand() % 10) / 10.0;
	firework->r = rand_color();
	firework->g = rand_color();
	firework->b = rand_color();
	firework->radius = 0;
}

void fireworks_init(Level *lev)
{
	int i;

	level = lev;
	
	for (i=0; i<NUM_FIREWORKS; ++i) {
		init_firework(&fireworks[i]);
	}
}

void fireworks_run()
{
	int i;

	for (i=0; i<NUM_FIREWORKS; ++i) {
		if (fireworks[i].z < EXPLODE_HEIGHT)
			fireworks[i].z += fireworks[i].speed;
		else {
			// explode

			fireworks[i].radius += 0.2;

			if (fireworks[i].radius > 1.5)
				init_firework(&fireworks[i]);
		}
	}
}

void fireworks_draw()
{
	int i;

	for (i=0; i<NUM_FIREWORKS; ++i) {
		glPushMatrix();

		glTranslatef(fireworks[i].x, fireworks[i].y, fireworks[i].z);
		
		if (fireworks[i].z < EXPLODE_HEIGHT) {
			glScalef(0.1, 0.1, 0.1);
			glColor3f(1, 1, 1);
			draw_cylinder(6);
		} else {
			glScalef(fireworks[i].radius, fireworks[i].radius,
				 fireworks[i].radius);
			glColor3f(fireworks[i].r, fireworks[i].g,
				  fireworks[i].b);
			draw_sphere(10, 10);				 
		}

		glPopMatrix();
	}
}
