#include "linux_utilities/plugin_editor_base.h"
#include "../backend/wb_editor_storednote.h"
#include "linux_utilities/MGGladeXML.h"
#include "gtk_helpers.h"
#include <gtkmm/textview.h>
#include <gtkmm/button.h>
#include <gtkmm/entry.h>
#include <gtkmm/box.h>

class StoredNoteEditor : public PluginEditorBase
{
  StoredNoteEditorBE _be;
  MGGladeXML *_xml;

  virtual bec::BaseEditor *get_be()
  {
    return &_be;
  }
  
  void load();
  void save();
  void apply();
  void discard();
  
public:
  StoredNoteEditor(grt::Module *m, bec::GRTManager *grtm, const grt::BaseListRef &args)
    : PluginEditorBase(m, grtm, args), _be(grtm, GrtStoredNoteRef::cast_from(args[0]))
  {
    set_border_width(8);
    
    _xml= new MGGladeXML(grtm->get_data_file_path("modules/data/editor_storednote.glade"));

    Gtk::VBox* box(0);
    _xml->get("vbox1", &box);
    box->reparent(*this);

    show_all();
    
    refresh_form_data();
    
    Gtk::Button* btn(0);
    _xml->get("load", &btn);
    btn->signal_clicked().connect(sigc::mem_fun(this, &StoredNoteEditor::load));

    _xml->get("save", &btn);
    btn->signal_clicked().connect(sigc::mem_fun(this, &StoredNoteEditor::save));

    _xml->get("apply", &btn);
    btn->signal_clicked().connect(sigc::mem_fun(this, &StoredNoteEditor::apply));

    _xml->get("discard", &btn);
    btn->signal_clicked().connect(sigc::mem_fun(this, &StoredNoteEditor::discard));
  }
  
  virtual ~StoredNoteEditor()
  {
    delete _xml;
  }

  virtual void do_refresh_form_data()
  {    
    Gtk::TextView* text(0);
    _xml->get("note", &text);
    bool is_utf8 = false;
    text->get_buffer()->set_text(_be.get_text(is_utf8));
  }
  
  virtual std::string get_title()
  {
    return _be.get_name();
  }
};

//------------------------------------------------------------------------------
void StoredNoteEditor::load()
{
  const std::string file = open_file_chooser();
  if ( !file.empty() )
  {
    _be.load_file(file);
    do_refresh_form_data();
  }
}

//------------------------------------------------------------------------------
void StoredNoteEditor::save()
{
  const std::string file = open_file_chooser();
  if ( !file.empty() )
  { 
    apply();
    _be.save_file(file);
    do_refresh_form_data();
  }
}

//------------------------------------------------------------------------------
void StoredNoteEditor::apply()
{
  Gtk::TextView* text(0);
  _xml->get("note", &text);
  _be.set_text(text->get_buffer()->get_text());
}

//------------------------------------------------------------------------------
void StoredNoteEditor::discard()
{
  do_refresh_form_data();
}

extern "C" 
{
  GUIPluginBase *createStoredNoteEditor(grt::Module *m, bec::GRTManager *grtm, const grt::BaseListRef &args)
  {
    return Gtk::manage(new StoredNoteEditor(m, grtm, args));
  }
};
