#include "../include/zf.h"

/* in frames */
#define SCORE_LIFE 200  

typedef struct Score Score;

struct Score
{
    unsigned int ref_count;

    CLmatrix frame;

    CLcolour colour;
    int age;
    char value[10];  /*hack, should be enough */

};

static ZfSmartPointer smart_pointer; /* interface for missiles */
static ZfDynamicCollider dynamic_collider; /* interface for scores */

static bool
is_valid(const Score* score)
{
    return score->age < SCORE_LIFE;
}

static void
reference(Score* score)
{
    score->ref_count++;
}

static void
release(Score* score)
{
    score->ref_count--;

    if (score->ref_count == 0)
	g_free(score);
}

static void
animate(Score* score)
{
    score->age++;
}

static void
render(Score* score)
{
    CLvertex ship_pos;
    CLnormal z_axis,up;
    CLvertex score_pos;


    zf_ship_query_position(&ship_pos);
    cluSetNormal(&up, 0.0f, 1.0f, 0.0f);
    cluSetVertexMatrixOrigin(&score_pos, &score->frame);
    cluNormalDifference(&z_axis, &ship_pos, &score_pos);

    zf_align_frame_y_vertex_normal(&score->frame, &score_pos, &up);
    zf_align_frame_z_vertex_normal(&score->frame, &score_pos, &z_axis);


    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glPushMatrix();
       
    glDisable(GL_LIGHTING);
    glDisable(GL_COLOR_MATERIAL);
    
    glMultMatrixf((GLfloat*)&score->frame);
    
    glColor4f(score->colour.r, 
	      score->colour.g, 
	      score->colour.b, 
	      1.0f - (float)score->age / (float)SCORE_LIFE); 
    

    glLineWidth(2.0f);
    zf_text_draw(score->value);

    glPopMatrix();
    glPopAttrib();
}

void
zf_score_indicator_close(void)
{
}

void
zf_score_indicator_init(void)
{
    smart_pointer.is_valid = (ZfIsValid*) is_valid;
    smart_pointer.reference = (ZfReference*) reference;
    smart_pointer.release = (ZfRelease*) release;

}

void	
zf_score_indicator_new(const CLvertex* position, const int score_value)
{
    Score* score;
    CLnormal z_axis;
    score = g_new(Score, 1);

    score->ref_count = 0;
    zf_ship_query_frame(&score->frame);

    cluSetNormalMatrixAxisZ(&z_axis, &score->frame);
    cluNormalScale(&z_axis, -1.0f);

    zf_align_frame_z_vertex_normal(&score->frame, (CLvertex*) position, &z_axis);
    
  
    score->age = 0;
 
    sprintf(score->value,"%d\0",score_value);

    if(score_value > 100)
	cluSetColour(&score->colour, 0.62f, 0.27f, 0.87f, 1.0f);
    else if(score_value > 250)
	cluSetColour(&score->colour, 0.27f, 0.56f, 0.87f, 1.0f);
    else if(score_value > 500)
	cluSetColour(&score->colour, 0.27f, 0.88f, 0.33f, 1.0f);
    else
	cluSetColour(&score->colour, 1.0f, 1.0f, 0.0f, 1.0f);

    zf_animation_system_add(score,
			    &smart_pointer, 
			    (ZfAnimate*) animate);
    
    zf_render_system_add_translucent(score,
				     &smart_pointer,
				     (ZfRender*) render);
}
