# Date_Window.pm
# Date entry window for crashman3
# $Id$
package Date_Window;

use strict;
use Date::Format;
use Crashbackend;

use CSL::Gnome2;
use Gnome2;
use Gtk2::GladeXML;
use Gtk2::Gdk::Keysyms;

sub new
{
    my $this = shift;
    my $class = ref($this) || $this;

    bless (my $self = {}), $class;

    my $GLADEDIR = $main::GLADEDIR || ".";
    $self->{xml} = Gtk2::GladeXML->new("$GLADEDIR/crashman3.glade",
                                       'date_window');
    die "Error opening Glade file" if !$self->{xml};    
    $self->{xml}->signal_autoconnect_from_package($self);

    return $self;
}

sub run
{
    my ($class) = @_;

    Gnome2::Program->init("crashman", "3");

    my $self = $class->new;

    Gtk2->main;
    return $self->{due_date} or undef;
}

sub on_ok_button_clicked
{
    my ($self) = @_;

    my $due_date_text = $self->wgt('date_entry')->get_text;

    my $due_date = Crashbackend::parse_due_date($due_date_text);
    if (!$due_date)
    {
        my $box = Gtk2::MessageDialog->new(
                    undef, 'destroy-with-parent', 'error', 'ok',
                    "$due_date_text is not a valid date.\n" .
                    "Please enter a valid date (MM/DD/YYYY)");
        $box->run;
        $box->destroy;
        return;
    }

    if (Crashbackend::late_due_date($due_date_text))
    {
        my $box = Gtk2::MessageDialog->new(
                    undef, 'destroy-with-parent', 'warning', 'yes-no',
                    "The date $due_date_text is later than the current ".
                    "limit of ".Crashbackend::get_end_semester_date().".\n".
                    "Are you sure you want to check this disk out to ".
                    "this date?\n");
        my $r = $box->run;
        $box->destroy;
        if ($r eq 'no')
        {
            return;
        }
    }

    $self->{due_date} = time2str("%D", $due_date);
    $self->wgt('date_window')->destroy;
    Gtk2->main_quit;
}

sub on_cancel_button_clicked
{
    my ($self) = @_;

    undef $self->{due_date};
    $self->wgt('date_window')->destroy;
    Gtk2->main_quit;
}

sub on_date_window_delete_event
{
    $_[0]->on_cancel_button_clicked;
}

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

    if ($event->keyval == $Gtk2::Gdk::Keysyms{Return} ||
        $event->keyval == $Gtk2::Gdk::Keysyms{KP_Enter}) {
        $self->on_ok_button_clicked;
        1;
    } elsif ($event->keyval == $Gtk2::Gdk::Keysyms{Escape}) {
        $self->on_cancel_button_clicked;
        1;
    }

    0; # pass to next handler
}

sub wgt { return $_[0]->{xml}->get_widget($_[1]); }

1;


