

#include "history_tree.h"
#include "workbench/wb_history_tree.h"

HistoryTree::HistoryTree(wb::WBContextUI *wbui)
  : _wbui(wbui)
{
  set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
  add(_tree);
  set_shadow_type(Gtk::SHADOW_IN);
  _tree.set_headers_visible(false);
  _tree.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);

  show_all();
 
  _model= TreeModelWrapper::create(_history= _wbui->get_history_tree(), &_tree, "HistoryTree");
  _model->model().append_string_column(bec::ValueTreeBE::Name, "", RO, NO_ICON);
  _tree.set_model(_model);
  _model->set_fe_menu_handler(sigc::mem_fun(this, &HistoryTree::handle_menu));
  
  _tree.signal_row_activated().connect(sigc::mem_fun(this, &HistoryTree::activate_row));
  
  _last_count= 0;
}


void HistoryTree::refresh()
{
  _model->set_be_model(0);

  _tree.unset_model();
  _tree.set_model(_model);

  _model->set_be_model(_history);

  _tree.unset_model();
  _wbui->get_history_tree()->refresh();
  _tree.set_model(_model);

/*  int new_count= _wbui->get_history_tree()->count();

  if (new_count == _last_count + 1 && new_count > 0)
  {
    Gtk::TreePath path;

    path.push_back(new_count-1);

    _model->row_inserted(path, _model->get_iter(path));
  }
  else
  {
    _tree.unset_model();
    _tree.set_model(_model);
  }
  _last_count= _wbui->get_history_tree()->count();
 */
}


void HistoryTree::activate_row(const Gtk::TreeModel::Path &path, Gtk::TreeViewColumn *column)
{
  _history->activate_node(_model->get_node_for_path(path));
}

void HistoryTree::handle_menu(const std::string&, const std::vector<bec::NodeId>& nodes)
{
  std::string text;
  std::string line;

  if (nodes.size() == 1)
  {
    const int size = _history->count_children(bec::NodeId());

    for (int i = 0; i < size; ++i)
    {
      _history->get_field(bec::NodeId(i), wb::HistoryTreeBE::Description, line);
      text += line;
      text += '\n';
    }
  }
  else
  {
    for (int i = 0; i < nodes.size(); ++i)
    {
      _history->get_field(nodes[i], wb::HistoryTreeBE::Description, line);
      text += line;
      text += '\n';
    }
  }

  Glib::RefPtr<Gtk::Clipboard> cb = Gtk::Clipboard::get();

  cb->set_text(text);
  cb->store();
}
