#include "GUIFont.h"

GUIFont::GUIFont(char* name)
{
  initialized  = false;
  fontBase     = -1;
  height       = 12;
  width        = 6;
  this->name   = name;
  r=g=b=1.0f;
}

GUIFont::~GUIFont() {}

bool GUIFont::init()
{
  HFONT fontObject;
  fontObject  = CreateFont(height, width, 0, 0,
                           FW_BOLD, // weight
						   false, // italic
						   false, // underline
						   false, // strike
                           ANSI_CHARSET,
						   OUT_TT_PRECIS,
                           CLIP_DEFAULT_PRECIS, 
						   ANTIALIASED_QUALITY,
                           FF_DONTCARE|DEFAULT_PITCH,
                           name);
  
  fontBase = glGenLists(96);
  SelectObject(wglGetCurrentDC(), fontObject);
  wglUseFontBitmaps(wglGetCurrentDC(), 32, 96, fontBase);
  initialized = true;
  
  bool b = (fontObject != NULL);
  DeleteObject(fontObject);
  return b;
}

void GUIFont::destroy()
{
	glDeleteLists(fontBase, 96);
}

int  GUIFont::getFontBase()
{
  return fontBase;
}

bool GUIFont::isInitialized()			{ return initialized; }
void GUIFont::setHeight(int height_)	{ if(initialized) return; height = height_; }
int  GUIFont::getHeight()				{ return height;    }
void GUIFont::setWidth(int width_)		{ if(initialized) return; width = width_; }
int  GUIFont::getWidth()				{ return width;   }


void GUIFont::setColor(float r_, float g_, float b_)
{
	this->r = r_;
	this->g = g_;
	this->b = b_;
}

void GUIFont::print(const char *str, int x, int y) 
{
  glColor3f(r,g,b);
  glRasterPos2i(x, y);
  glPushAttrib(GL_LIST_BIT);
	glListBase(this->getFontBase() - 32);
	glCallLists(int(strlen(str)), GL_UNSIGNED_BYTE, str);
  glPopAttrib();
}

void GUIFont::printCenteredX(const char *str, int x, int y)
{
	int w_ = calculateWidth(str);
	print(str, x - w_/2, y);
}

void GUIFont::printCenteredY(const char *str, int x, int y)
{
	int h_ = calculateHeight(str);
	print(str, x, y - h_/3);
}

void GUIFont::printCenteredXY(const char *str, int x, int y)
{
	int w_ = calculateWidth(str);
	int h_ = calculateHeight(str);
	
	print(str, x - w_/2, y + h_/3); // h/3 (?)
}

int GUIFont::calculateWidth(const char *str)
{
	// lasketaan leveys piirtämällä tyhjää ja laskemalla paljon kirjoituspääsiirtyi
    glColorMask(false, false, false, false);
    glRasterPos2i(0,0);
    glPushAttrib(GL_LIST_BIT);
		glListBase(getFontBase() - 32);
		glCallLists(strlen(str), GL_UNSIGNED_BYTE, str);
    glPopAttrib();
	int rasterPosition[4];
    glGetIntegerv(GL_CURRENT_RASTER_POSITION, rasterPosition);
    glColorMask(true, true, true, true);

	return rasterPosition[0];
}

int GUIFont::calculateHeight(const char *str)
{
	return getHeight();
}
