#!/usr/bin/perl -w

use strict;
use warnings;

use Gtk2 -init;
use Gtk2::GladeXML;

my $glade_file = 'form_test.glade';

my $gui = Gtk2::GladeXML->new($glade_file);

my $controller = AppController->new($gui, 'form_test');

Gtk2->main;

exit;

package AppController;

use Glib qw(TRUE FALSE);

my %type_sigs;

sub new {
  my($class, $gui, $window_name) = @_;

  my $self = bless {}, $class;

  $self->attach_signals($gui->get_widget($window_name));

  return $self;
}

sub attach_signals {
  my($self, $widget) = @_;

  if(my $name = $widget->get_name) {
    foreach my $signame (@{ $self->list_signals(ref($widget)) }) {
      my $handler = "${name}_${signame}";
      $handler =~ s{\W}{_}g;
      if($self->can($handler)) {
        $widget->signal_connect(
          $signame => sub { $self->$handler(@_) }
        );
      }
    }
  }

  return unless $widget->can('get_children');
  foreach my $child ($widget->get_children) {
    $self->attach_signals($child);
  }

}

sub list_signals {
  my($self, $type) = @_;

  return $type_sigs{$type} if $type_sigs{$type};

  my %sigs;
  foreach my $siginfo (Glib::Type->list_signals($type)) {
    $sigs{$siginfo->{signal_name}}++;
  }
  foreach my $ancestor (Glib::Type->list_ancestors($type)) {
    next if $ancestor eq $type;
    $sigs{$_}++ foreach @{ $self->list_signals($ancestor) };
  }
  return $type_sigs{$type} = [ keys %sigs ];
}

sub form_test_delete_event {
  print "Window closed\n";
  Gtk2->main_quit();
  FALSE;
}

sub first_name_map_event {
  my($self, $entry) = @_;

  $entry->set_text('Eustace');
}

sub first_name_activate {
  my($self, $entry) = @_;

  print "Enter was pressed in the first name field\n";
}

sub first_name_focus {
  my($self, $entry) = @_;

  return unless$entry->has_focus;

  my $text = $entry->get_text;
  print "Tabbed away from first name: $text\n";
  return FALSE;
}

sub cancel_clicked {
  my($self, $button) = @_;

  print "Cancel button was clicked\n";
}

sub save_clicked {
  my($self, $button) = @_;

  print "Save button was clicked\n";
}

