

#include "layer_tree.h"
#include "treemodel_wrapper.h"
#include "image_cache.h"
#include "workbench/wb_layer_tree.h"

LayerTree::LayerTree(wb::WBContextUI *wbui)
  : _wbui(wbui)
  , _column(0)
{
  set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
  add(_tree);
  set_shadow_type(Gtk::SHADOW_IN);
  _tree.set_headers_visible(true);
  
  _layer_tree= (wb::LayerTreeBE*)_wbui->get_layer_tree();

  show_all();

  if (!_model)
  {
    _column= new Gtk::TreeModelColumn<Glib::RefPtr<Gdk::Pixbuf> >();
    Gtk::TreeViewColumn *vcolumn= new Gtk::TreeViewColumn("");

    Gtk::CellRendererPixbuf *prend= new Gtk::CellRendererPixbuf();
    vcolumn->pack_start(*prend, true);

    _model= TreeModelWrapper::create(_layer_tree, &_tree, "LayerTree", bec::NodeId(0));
    _model->model().add_generic_column(-1, _column, vcolumn);
    _model->model().append_string_column(bec::ValueTreeBE::Name, _("Layers & Figures"), RO, WITH_ICON);
    _tree.set_model(_model);

    vcolumn->add_attribute(prend->property_pixbuf(), *_column);

    _model->set_fake_column_value_getter(sigc::mem_fun(this, &LayerTree::get_tree_value));
  }
  
  _tree.signal_row_activated().connect(sigc::mem_fun(this, &LayerTree::activate_row));
}

LayerTree::~LayerTree()
{
  delete _column;
}

void LayerTree::refresh()
{
  if (!_selected_icon)
  {
    _selected_icon= ImageCache::get_instance()->image_from_filename("layer_selected.png", false);
    _unselected_icon= ImageCache::get_instance()->image_from_filename("layer_unselected.png", false);
    _mixed_icon= ImageCache::get_instance()->image_from_filename("layer_mixed.png", false);
  }
  
  _tree.unset_model();
  _layer_tree->refresh();
  _tree.set_model(_model);

  reexpand_nodes();
}


bool LayerTree::reexpand_node(const Gtk::TreePath &path)
{
  if (_layer_tree->is_expanded(_model->get_node_for_path(path)) || path.get_depth() <= 2)
    _tree.expand_to_path(path);

  return true;
}


void LayerTree::reexpand_nodes()
{
  _model->foreach_path(sigc::mem_fun(this, &LayerTree::reexpand_node));
}


void LayerTree::get_tree_value(const Gtk::TreeModel::iterator &iter, int column, Glib::ValueBase& value)
{
  bec::NodeId node= _model->node_for_iter(iter);
  std::string sel;
  
  _layer_tree->get_field(node, wb::LayerTreeBE::Selected, sel);

  g_value_init(value.gobj(), GDK_TYPE_PIXBUF);

  if (sel == "")
    g_value_set_object(value.gobj(), _unselected_icon->gobj());
  else if (sel == "X")
    g_value_set_object(value.gobj(), _selected_icon->gobj());
  else
    g_value_set_object(value.gobj(), _mixed_icon->gobj());
}



void LayerTree::activate_row(const Gtk::TreePath &path, Gtk::TreeViewColumn *column)
{
  bec::NodeId node= _model->node_for_iter(_model->get_iter(path));
  
  _layer_tree->activate_node(node);
}
