#include <FL/x.H>
#include <FL/Fl.H>
#include <config.h>
#include <global.hpp>

#include <prefs.hpp>

#include <font_factory.hpp>


extern Preferences  __pref;


font_factory::font_factory(){
  set_actual_font_from_prefs();
}
  
font_factory::~font_factory(){

}


Fl_Font font_factory::get_actual_font(Fl_Font alias){
  Fl_Font res=FL_HELVETICA;
  if(_fonts.count(alias)>0){
    res=_fonts[alias];
  }
  return res;
}

void font_factory::search_for_font(const char* desidered, Fl_Font destination, int num_fonts){
  for (int i = 0; i < num_fonts; i++) {
    const char *name = Fl::get_font_name((Fl_Font)i,NULL);
    if(strcasecmp (desidered,name)==0){
      std::pair<Fl_Font,Fl_Font> tmp(destination,(Fl_Font)i);
      _fonts.insert(tmp);
      break;
    }
  }
}


void font_factory::set_actual_font_from_prefs(){
  int n=Fl::set_fonts(NULL);
  search_for_font(__pref.get_sans_font().c_str(),FL_HELVETICA,n);
  search_for_font(__pref.get_sans_font().c_str(),FL_HELVETICA,n);
  search_for_font(__pref.get_sans_font_bold().c_str(),FL_HELVETICA_BOLD,n);
  search_for_font(__pref.get_sans_font_italic().c_str(),FL_HELVETICA_ITALIC,n);
  search_for_font(__pref.get_sans_font_bold_italic().c_str(),FL_HELVETICA_BOLD_ITALIC,n);
  search_for_font(__pref.get_mono_font().c_str(),FL_COURIER,n);
  search_for_font(__pref.get_mono_font_bold().c_str(),FL_COURIER_BOLD,n);
  search_for_font(__pref.get_mono_font_italic().c_str(),FL_COURIER_ITALIC,n);
  search_for_font(__pref.get_mono_font_bold_italic().c_str(),FL_COURIER_BOLD_ITALIC,n);
  search_for_font(__pref.get_serif_font().c_str(),FL_TIMES,n);
  search_for_font(__pref.get_serif_font_bold().c_str(),FL_TIMES_BOLD,n);
  search_for_font(__pref.get_serif_font_italic().c_str(),FL_TIMES_ITALIC,n);
  search_for_font(__pref.get_serif_font_bold_italic().c_str(),FL_TIMES_BOLD_ITALIC,n);
  search_for_font(__pref.get_symbol_font().c_str(),FL_SYMBOL,n);
  search_for_font(__pref.get_mono_font().c_str(),FL_SCREEN,n);
  search_for_font(__pref.get_mono_font_bold().c_str(),FL_SCREEN_BOLD,n);
  search_for_font(__pref.get_dingbats_font().c_str(),FL_ZAPF_DINGBATS,n);

}




font_factory* font_map_singleton::get_context(){
  if(font_map_singleton::factory==NULL){
    font_map_singleton::factory=new font_factory();
  }

  return font_map_singleton::factory;
}

void font_map_singleton::free_context(){
  delete font_map_singleton::factory;
}

bool font_map_singleton::works(){
  return font_map_singleton::factory;
}


font_map_singleton::font_map_singleton(){}


font_factory* font_map_singleton::factory=NULL;
