#include "ui.h"

#ifdef WIN32
  #include "windows.h"
  
  void w_hide_console() 
  {
    FreeConsole();
    
    // http://www.codeguru.com/forum/showthread.php?t=372610&p=1313157
    // hides console even if launched from console =p
    /*
    typedef HWND (WINAPI *tGetConsoleWindow)(void);
    tGetConsoleWindow pGetConsoleWindow = 0;
    HINSTANCE handle =  ::LoadLibrary("Kernel32.dll");
    if ( handle ) 
      pGetConsoleWindow = (tGetConsoleWindow)::GetProcAddress(handle, "GetConsoleWindow");     
    if ( pGetConsoleWindow ) 
    {
      HWND hwnd = pGetConsoleWindow();
      ::ShowWindow(hwnd,SW_HIDE);
    }
    if ( handle )
      ::FreeLibrary(handle);
    */
  }
#endif
  
  
  
GrabPngUI::GrabPngUI()  : _GrabPngUI()
{

  #ifdef WIN32
    w_hide_console();
  #endif
  
  Fl::visual(FL_DOUBLE | FL_INDEX);
  Fl::get_system_colors();
  fl_register_images();
  //Fl::scheme("plastic");
  
  config = new Config(".grabpng-config");
  
  if (config->get_i("ok"))
  {  
    mainWindow->position(config->get_i("x"),config->get_i("y"));
    mainWindow->size(config->get_i("w"),config->get_i("h"));
    
    bgcolor->rgb(config->get_f("r"),config->get_f("g"),config->get_f("b"));
    bgcolor->do_callback();
    
    imageBox->file_open(config->get("file").c_str());
  }
  
}

GrabPngUI::~GrabPngUI()
{
  delete config;
}

// imagebox callback
void GrabPngUI::imagebox_cb(ImageBox *o, void *v)
{
  Enums::ActionType *axn = (Enums::ActionType*)v;


  if(*axn==Enums::gpRELEASE)
  {
    o->center();
    save->activate();
    
    o->image_x(o->img_x);
    o->image_y(o->img_y);
    o->scrollArea->redraw();
  }

  else if(*axn==Enums::gpLOAD)
  {
    alph->value(o->image_alph); 
    label->label(o->base_filename());
    o->center();
    save->deactivate();
  }
  
  //if(*axn==Enums::gpDRAG)
  {
    grabX->value(o->image_x());
    grabY->value(o->image_y());
  }
  
}

// colorpicker callback
void GrabPngUI::colorpicker_cb()
{
  
  Fl_Color_Chooser *o = bgcolor;
  
  
  unsigned char r = (unsigned char)(o->r() * 255.0);
  unsigned char g = (unsigned char)(o->g() * 255.0);
  unsigned char b = (unsigned char)(o->b() * 255.0);
  
  Fl_Color c = fl_rgb_color(r,g,b);
  
  imageBox->color(c);
  mainWindow->redraw();
  
}

// handle close event
void GrabPngUI::window_cb() 
{
  config->set("ok",1);
  
  config->set("x",mainWindow->x());
  config->set("y",mainWindow->y());
  config->set("w",mainWindow->w());
  config->set("h",mainWindow->h());
  
  config->set("r",bgcolor->r());
  config->set("g",bgcolor->g());
  config->set("b",bgcolor->b());
  
  config->set("file",imageBox->current_filename);
  
  config->save();
  
  exit(0);
}
