#include "output_box.h"
#include "grt/grt_manager.h"
#include "menu_manager.h"

OutputBox::OutputBox(bec::GRTManager *grtm)
{
  set_tab_pos(Gtk::POS_BOTTOM);

  append_page(_message_swin, _("Messages"));
  _message_swin.add(_message_tree);
  _message_swin.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
  _message_swin.set_shadow_type(Gtk::SHADOW_IN);
  _message_swin.signal_button_release_event().connect(sigc::mem_fun(this, &OutputBox::process_event_button));

  _message_be= grtm->get_messages_list();
  _message_model= ListModelWrapper::create(_message_be, &_message_tree, "OutputBox");
  
  _message_be->signal_changed().connect(sigc::mem_fun(this, &OutputBox::refresh));

  _message_model->model().append_string_column(bec::MessageListBE::Message, _("Message"), RO, WITH_ICON);
  _message_model->model().append_string_column(bec::MessageListBE::Time, _("Time"), RO);
  
  _message_tree.set_model(_message_model);

  
  append_page(_output_swin, _("Output"));
  _output_swin.add(_output_text);
  _output_swin.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
  _output_swin.set_shadow_type(Gtk::SHADOW_IN);
  
  _output_text.set_editable(false);

  show_all();
  
  _message_be->set_refresh_ui_slot(sigc::mem_fun(this, &OutputBox::refresh));
}



void OutputBox::add_output(const std::string &text)
{
  _output_text.get_buffer()->insert(_output_text.get_buffer()->end(), text+"\n");
}



void OutputBox::refresh()
{
  _message_tree.unset_model();
  _message_be->refresh();
  _message_tree.set_model(_message_model);
  Gtk::TreePath path;
  path.append_index(_message_model->get_be_model()->count()-1);
  _message_tree.scroll_to_row(path);
}


//------------------------------------------------------------------------------
bool OutputBox::process_event_button(GdkEventButton* ev)
{
  if ( ev->type == GDK_BUTTON_RELEASE && ev->button == 3 )
  { 
    std::vector<bec::NodeId> nodes(1);
    nodes.push_back(bec::NodeId());
    
    bec::MenuItemList menuitems = _message_be->get_popup_items_for_nodes(nodes);

    MenuManager::run_and_forward_action(menuitems, ev->x, ev->y, ev->time, _message_be, nodes);
  }

  return false;  
}
