#include <math.h>
#include "text.h"
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include "gloutils.h"

void behaviour_gl_color_white (text_t* text, void* dummy) {
  float white[4] = { 1, 1, 1, 1 } ;
  behaviour_gl_color (text, white) ;
}

void behaviour_gl_color (text_t* text, void* data) {
  float* color = data ;
  glColor4fv (color) ;
}

void behaviour_gl_display (text_t* text, void* data) {
  int i;
  void* font = text->opaquedata ;
  char* string = text->source (text, text->sourcedata) ;
  if (font==NULL) font = GLUT_BITMAP_TIMES_ROMAN_24 ;
  for (i=0; i<strlen(string); i++) 
    glutBitmapCharacter (font, string[i]) ;
  free (string) ;
}

void behaviour_gl_font (text_t* text, void* data) {
  text->opaquedata = data ;
}

void behaviour_gl_position (text_t* text, void* data) {
  int position = (int)data ;
  void* font = text->opaquedata ; 
  char* string = text->source (text, text->sourcedata) ;
  int offset=0,x=1,y=1,stringwidth=glutBitmapLength (font,string) ;
  int w,h ;
  GLint viewport[4] ;
  glGetIntegerv (GL_VIEWPORT, viewport) ;
  w=viewport[2] ; h=viewport[3] ;

  if (font==GLUT_BITMAP_TIMES_ROMAN_24) offset=24 ;
  if (offset==0) {
    fprintf (stderr, 
	     "WARNING: unknown font (%x), assuming 24 points\n",
	     (int)font) ; 
    offset = 24 ;
  }
  
  switch (position) {
  case TEXT_GL_TOPLEFT: 
    y=-y-offset; break;
  case TEXT_GL_TOPRIGHT: 
    y=-y-offset; x=-x-stringwidth; break; 
  case TEXT_GL_BOTTOMLEFT: 
    break ;
  case TEXT_GL_BOTTOMRIGHT:
    x=-x-stringwidth ; break ;
  case TEXT_GL_TOPCENTER:
    y=-y-offset; x=x+(w-stringwidth)/2 ; break ;
  case TEXT_GL_BOTTOMCENTER:
    x=x+(w-stringwidth)/2; break ;
  case TEXT_GL_CENTER:
    x=x+(w-stringwidth)/2; y=y+(h-offset)/2 ; break ;
  default:
    x=y=50 ;
  }

  glouAbsoluteRasterPos3f (x,y,0.1) ;
  free (string) ;
}

void text_display (text_t* text) {
  int i;
  for (i=0; i<text->n_behaviours; i++)
    text->behaviours[i] (text, text->behaviourdata[i]) ;
}

void behaviour_gl_fadeinout (text_t* text, void* data) {
  float color[4] = { 1, 1, 1, 1 } ;
  color[3] *= fabs (cos (0.00314*glutGet (GLUT_ELAPSED_TIME))) ;
  behaviour_gl_color (text, color) ;
}
