#include "navigator_box.h"
#include "image_cache.h"

#include <gtkmm/image.h>

#include "workbench/wb_context_ui.h"
#include "workbench/wb_model_diagram_form.h"


static int zoom_levels[]= {
  200,
    150,
    100,
    95,
    90,
    85,
    80,
    75,
    70,
    60,
    50,
    40,
    30,
    20,
    10
};


NavigatorBox::NavigatorBox(wb::WBContextUI *wbui)
  : Gtk::VBox(false, 2), _wbui(wbui), _canvas(mdc::GtkCanvas::XlibCanvasType)
{
  Gtk::HBox *hbox= Gtk::manage(new Gtk::HBox(false, 0));

  _canvas.signal_realize().connect(sigc::mem_fun(this, &NavigatorBox::realized));
  _canvas.signal_size_allocate().connect(sigc::mem_fun(this, &NavigatorBox::size_change));
  
  pack_start(_canvas, true, true);
  pack_start(*hbox, false, false);
  
  Gtk::Image *image1= Gtk::manage(new Gtk::Image(ImageCache::get_instance()->image_from_filename("navigator_zoom_out.png")));
  Gtk::Image *image2= Gtk::manage(new Gtk::Image(ImageCache::get_instance()->image_from_filename("navigator_zoom_in.png")));

  _combo.set_name("zoom_combo");
  _combo.set_size_request(60, -1);
  _slider.set_draw_value(false);
  _slider.set_range(10, 200);
  _slider.signal_value_changed().connect(sigc::mem_fun(this, &NavigatorBox::slider_changed));
  _combo.signal_changed().connect(sigc::mem_fun(this, &NavigatorBox::combo_changed));

  for (unsigned int i= 0; i < sizeof(zoom_levels)/sizeof(int); i++)
    _combo.append_text(strfmt("%i", zoom_levels[i]));
  _combo.set_active_text("100");

  hbox->pack_start(*image1, false, false);
  hbox->pack_start(_slider, true, true);
  hbox->pack_start(*image2, false, false);
  hbox->pack_start(_combo, false, false);
  
  show_all();
}



void NavigatorBox::realized()
{
  _wbui->setup_mini_view(_canvas.get_canvas());
  _wbui->update_mini_view_size(_canvas.get_width(), _canvas.get_height());
}


void NavigatorBox::size_change(Gtk::Allocation &alloc)
{
  _wbui->update_mini_view_size(_canvas.get_width(), _canvas.get_height());
  _canvas.queue_draw();
}


void NavigatorBox::refresh()
{
  wb::ModelDiagramForm *form= dynamic_cast<wb::ModelDiagramForm*>(_wbui->get_active_main_form());

  int value= 100;

  if (form)
    value= (int)(form->get_zoom()*100);

  _slider.set_value(value);
  _combo.get_entry()->set_text(strfmt("%i", value));

  _slider.set_sensitive(form != 0);
  _combo.set_sensitive(form != 0);
}


void NavigatorBox::slider_changed()
{
  int value= (int)_slider.get_value();

  wb::ModelDiagramForm *form= dynamic_cast<wb::ModelDiagramForm*>(_wbui->get_active_main_form());
  if (form)
  {
    form->set_zoom(value/100.0);

    refresh();
  }
}


void NavigatorBox::combo_changed()
{
  wb::ModelDiagramForm *form= dynamic_cast<wb::ModelDiagramForm*>(_wbui->get_active_main_form());
  if (form)
  {
    form->set_zoom(atoi(_combo.get_entry()->get_text().c_str()) / 100.0);

    refresh();
  }
}

