#include "form_view_base.h"
#include "plugin_editor_base.h"
#include <gtkmm/box.h>
#include <gtkmm/label.h>
#include <gtkmm/eventbox.h>
#include <gtkmm/window.h>
#include "active_label.h"


bool FormViewBase::close_plugin_tab(PluginEditorBase *editor)
{
  if (editor->can_close())
  {
    _close_editor(editor);
    remove_plugin_tab(editor);
  }
  else
    return false;

  bool has_visible_tabs = false;
  for (int c= _editor_note->get_n_pages(), i= 0; i < c; i++)
  {
    if (_editor_note->get_nth_page(i)->is_visible())
    {
      has_visible_tabs = true;
      break;
    }
  }
  if (!has_visible_tabs)
    _editor_note->hide();

  return true;
}


void FormViewBase::set_close_editor_callback(const sigc::slot<void, PluginEditorBase*> &handler)
{
  _close_editor = handler;
}
  

void FormViewBase::add_plugin_tab(PluginEditorBase *plugin)
{
  if (_editor_note)
  {
    ActiveLabel* label = Gtk::manage(new ActiveLabel(plugin->get_title(), sigc::hide_return(sigc::bind(sigc::mem_fun(this, &FormViewBase::close_plugin_tab), plugin))));

    _editor_note->append_page(*plugin, *label);

    plugin->signal_title_changed().connect(sigc::mem_fun(label, &ActiveLabel::set_text));

    if (!_editor_note->is_visible())
    {
      _editor_note->show();
      reset_layout();
    }

    plugin_tab_added(plugin);
  }
  else
    g_warning("active form doesn't support editor tabs");
}



void FormViewBase::remove_plugin_tab(PluginEditorBase *plugin)
{
  if (_editor_note)
  {
    _editor_note->remove_page(*plugin);

    if (_editor_note->get_n_pages() == 0)
      _editor_note->hide();
  }
}


bool FormViewBase::close_editors_for_object(const std::string &id)
{
  for (int i= _editor_note->get_n_pages()-1; i >= 0; --i)
  {
    Gtk::Widget *panel= _editor_note->get_nth_page(i);
    PluginEditorBase* editor;
    if ((editor= dynamic_cast<PluginEditorBase*>(panel))
        && (id.empty() || editor->should_close_on_delete_of(id)))
    {
      remove_plugin_tab(editor);
      return true;
    }
  }

  return false;
}


PluginEditorBase *FormViewBase::get_focused_plugin_tab()
{
  if (_editor_note)
  {
    Gtk::Widget *focused= dynamic_cast<Gtk::Window*>(_editor_note->get_toplevel())->get_focus();

    // go up the hierarchy to see if the focused widget is inside _editor_note
    while (focused && focused != _editor_note)
      focused= focused->get_parent();
    
    if (focused)
    {
      int page= _editor_note->get_current_page();
      if (page >= 0)
      {
        Gtk::Widget *tab= _editor_note->get_nth_page(page);
        return dynamic_cast<PluginEditorBase*>(tab);
      }
    }
  }

  return 0;
}


bool FormViewBase::close_focused_tab()
{
  PluginEditorBase *active = get_focused_plugin_tab();

  if (active)
  {
    close_plugin_tab(active);
    return true;
  }

  return false;
}

