package notes;
#: Version: 2.0.0
#: Description: Assign notes to worlds
#: Author: Eduardo M Kalinowski

BEGIN {
  eval "use Gtk3 -init;";
  die "This plugin requires the gtk3-perl bindings" if $@;
}

$::world->makepermanent('$notes::notetext');


our $window_created = 0;
our $window;
our $text_buffer;


sub help {
  $::world->echonl("",
  "This plugin allows you to assign notes to World. The notes are saved",
  "with the World and are restored when it is opened again.",
  "",
  "Run /notes::edit to open a window where you can edit the notes.",
  "",
  "Run /notes::clear to clear the contents of the notes.",
  "",
  "It is possible to append something to the notes with /notes::append('text')",
  "This is probably more useful in scripts."
  );
}


sub edit {
  unless ($window_created) {
    create_window();
    $window->show_all();
    $window_created = 1;
  }

  $window->present;
}


sub clear {
  $notetext = "";
  update_text_view();
}


sub append {
  my $newtext = $_[0];
  $newtext .= "\n" unless (substr($_[0], -1) eq "\n");

  $notetext .= $newtext;
  update_text_view();
}


sub UNLOAD {
  if ($window_created) {
    update_text();
    $window->destroy;
  }
}


sub create_window {
  $window = Gtk3::Window->new;
  $window->set_title("Notes for " . $::world->getname());
  $window->signal_connect(delete_event => sub {
                            update_text();
                            $window->hide();
                            return 1;
                          });
  $window->signal_connect(focus_out_event => sub {
                            update_text();
                          });

  my $vbox = Gtk3::VBox->new;

  my $scroll_win = Gtk3::ScrolledWindow->new;
  $scroll_win->set_policy('never', 'always');

  my $text_view = Gtk3::TextView->new;
  $text_view->set_size_request(400, 150);
  $text_buffer = $text_view->get_buffer;
  update_text_view();

  $scroll_win->add($text_view);
  $vbox->pack_start($scroll_win, 1, 1, 0);

  my $btn_close = Gtk3::Button->new_with_mnemonic('_Close');
  $btn_close->signal_connect(clicked => sub {
                               update_text();
                               $window->hide;
                               $window_displayed = 0;
                             });
  $vbox->pack_start($btn_close, 0, 0, 0);

  $window->add($vbox);
}


sub update_text {
  $notetext = $text_buffer->get_text($text_buffer->get_bounds(), 0);
}


sub update_text_view {
  return unless $text_buffer;

  if (defined($notetext)) {
    $text_buffer->set_text($notetext);
  }
}
