/*
      _______                          .__ .__   .__   .__                 
      \      \    ____   __ __ _______ |__||  |  |  |  |__|  ____    ____  
      /   |   \ _/ __ \ |  |  \\_  __ \|  ||  |  |  |  |  | /  _ \  /    \ 
     /    |    \\  ___/ |  |  / |  | \/|  ||  |__|  |__|  |(  <_> )|   |  \
     \____|__  / \___  >|____/  |__|   |__||____/|____/|__| \____/ |___|  /
    =========\/======\/=================================================\/==
  v0.01 04/JUL/2007 (C) Copyright 2007-2007 Scott D. Yelich SOME RIGHTS RESERVED
 .,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.-*~'`^`'~*-,._.,-*~'`^`'~*-,. 


  LICENSE:  Creative Commons Attribution 3.0 License.
  SEE:      http://creativecommons.org/licenses/by/3.0/


  Sun Jul 29 21:33:38 EDT 2007, v0.02 sdy

  This is a *very* simple program written to do a web page
  hit counter using sqlite3.

*/

//  LDFLAGS= -lgd -lpng -lz -ljpeg -lfreetype -lm

//  LOCAL

#include "Gd.h"
#include <iostream>
#include <fstream>

Gd::Gd()
{
  sz = 12.;
  fgr = 0;
  fgg = 0;
  fgb = 0;
  std::string f("default.ttf");
  set_font(f);
}

Gd::~Gd()
{
  /* Destroy it */
  gdImageDestroy(im);
}

Gd &
Gd::make_img( std::string & str )
{

  char * s = new char[str.size()+1];
  memcpy(s, str.c_str(), str.size()+1);
  char * f = new char[font.size()+1];
  memcpy(f, font.c_str(), font.size()+1);

  /* bounding rectangle */
  err = gdImageStringFT(NULL,&brect[0],0,f,sz,0.,0,0,s);
  //  if (err) {fprintf(stderr,err); return 1;}
 
  /* create an image big enough for the string plus a little whitespace */
  x = brect[2]-brect[6] + 6;
  y = brect[3]-brect[7] + 6;
  im = gdImageCreate(x,y);
 
  /* Background color (first allocated) */
  backg = gdImageColorResolve(im, 192, 192, 192);
  gdImageColorTransparent (im, backg);
  white = gdImageColorResolve(im, 255, 255, 255);
  black = gdImageColorResolve(im, 0, 0, 0);
  color = gdImageColorResolve(im, fgr, fgg, fgb);
 
  /* render the string, offset origin to center string*/
  /* note that we use top-left coordinate for adjustment
   * since gd origin is in top-left with y increasing downwards. */
  x = 3 - brect[6];
  y = 3 - brect[7];
  err = gdImageStringFT(im,&brect[0],color,f,sz,0.0,x,y,s);
  delete[] s;
  delete[] f;
//  if (err) {fprintf(stderr,err); return 1;}
  return *this;
}

Gd &
Gd::to_stdout()
{
  /* Write img to stdout */
  gdImagePng(im, stdout);
  //  gdImageGif(im, stdout);
  return *this;
}

Gd &
Gd::to_file()
{
/*
  FILE *pngout;
  pngout = fopen("f.png", "wb");
  gdImagePng(im, pngout);
  fclose(pngout);
*/
  return *this;
}

Gd &
Gd::set_point_size ( int point_size )
{
  sz = point_size;
  return *this;
}

Gd &
Gd::set_font ( std::string & font_name )
{
  font = "/www/neurillion/p/33/fonts/ttf/";
  font.append(font_name);
  std::ifstream file(font.c_str());
  if ( ! file ) {
    font = "/www/neurillion/p/33/fonts/ttf/default.ttf";
  }
  return *this;
}

Gd &
Gd::set_RGB ( int r, int g, int b )
{
  fgr = r;
  fgg = g;
  fgb = b;
  return *this;
}
