#=====================================================================#
#                                                                     #
# This is the 'User_Window' class                                     #
#                                                                     #
#=====================================================================#
# $Id$

package User_Window;
use strict;
our $USER;
use CSL::Gnome2;
use Gnome2;
use Gtk2::GladeXML;
use CSL::DBs;
use Carp;
use Gtk2::Gdk::Keysyms;

use Alert_Window;

our $GLADEPATH = '/s/lab/common/lib/library5';

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

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

# TODO Do I need to parse rc file here too?

    $self->{xml} = Gtk2::GladeXML->new("$GLADEPATH/library.glade",
                                'user_window');
    croak "Error opening Glade file" if (!$self->{xml});

    $self->{xml}->signal_autoconnect_from_package($self);

    return $self;
}

sub run
{
    my ($class, $function, $isbn, $caption, $main_window) = @_;

    Gnome2::Program->init("library", "5");

    my $self = $class->new;

    $self->wgt('prompt_label')->set_text($caption);

    $self->wgt('user_window')->show;

    $self->{function} = $function;
    $self->{isbn} = $isbn;
    $self->{main_window} = $main_window;

    Glib::Timeout->add(500, \&do_scan, $self);
}

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

    my $function = $self->{function};
    my $isbn = $self->{isbn};

    my $dbh = DBI->connect($CSL::DBs::csdb);
    $dbh->do("set search_path to library");

    my $user = $self->wgt('user_entry')->get_text();
    # Check to see if the user has been admonished; if so, can't do anything
    # with that user except unadmonish them.
    if ($function ne "unadmonish" &&
       (my $message = &Main_Window::admonished($user)))
    {
        Alert_Window->run($user . " has been admonished: $message");
        $dbh->disconnect();
        $self->wgt('user_window')->destroy();
        return;
    }

    # Check how many overdue books user has.
    my $query = $dbh->prepare("SELECT count(*) FROM books " .
                               "WHERE usr = ? AND status = 'Overdue'");
    $query->execute($user);
    my ($books) = $query->fetchrow();
    $query->finish();
    if ($books > 0 && ($function eq "out" || $function eq "recall"))
    {
        Alert_Window->run($user . " has too many overdue books: $books");
        $dbh->disconnect();
        $self->wgt('user_window')->destroy();
        return;
    }

    if (!getpwnam($user) && $function ne "admonish-1")
    {
        Alert_Window->run("That user doesn't exist: $user");
    }

    if ($function eq "out")
    {
        if (&Main_Window::recalled($isbn, $user))
        {
            Alert_Window->run("That book has been recalled.");
        }
        else
        {
            my $query = $dbh->prepare("DELETE FROM recall " .
                                      "WHERE book = ? " .
                                      "AND username = ?");
            $query->bind_param(1, $isbn);
            $query->bind_param(2, $user);
            $query->execute();
            $query->finish();
        }

        my $add = 3;
        my $query = $dbh->prepare("SELECT date_part('dow', CURRENT_DATE + $add)");
        $query->execute();
        my ($dow) = $query->fetchrow();
        $add += 2 if ($dow == 0 || $dow == 1 || $dow == 6);
        $query->finish();

        my $munged_isbn = $isbn;
        $isbn =~ s/-//g;
        my $copy = 0;
        if ($isbn =~ /^(.+)C(\d+)$/)
        {
            $isbn = $1;
            $copy = $2;
        }

        $query = $dbh->prepare("UPDATE books " .
                               "SET status = 'Checked Out', " .
                               "usr = ?, " .
                               "due = CURRENT_DATE + $add " .
                               "WHERE isbn = ? AND " .
                               "cpy = ?");
        $query->bind_param(1, $user);
        $query->bind_param(2, $isbn);
        $query->bind_param(3, $copy);
        $query->execute();
        $query->finish();

        chomp(my $me = `whoami`);
        $query = $dbh->prepare("INSERT INTO log VALUES " .
                               "(?, ?, ?, CURRENT_TIMESTAMP, ?)");
        $query->bind_param(1, $user);
        $query->bind_param(2, "Checked Out");
        $query->bind_param(3, $munged_isbn);
        $query->bind_param(4, $me);
        $query->execute();
        $query->finish();

        $self->{main_window}->unselect_all();
        $self->{main_window}->getbooks();
        $self->{main_window}->getcds();
        $self->{main_window}->getlaptops;
        $self->{main_window}->getkeys;
    }
    elsif ($function eq "lab")
    {
	my $munged_isbn = $isbn;
	$isbn =~ s/-//g;
	my $copy = 0;
	if ($isbn =~ /^(.+)C(\d+)$/)
	{
	    $isbn = $1;
	    $copy = $2;
	}

	my $query = $dbh->prepare("UPDATE books " .
				  "SET status = 'Lab', " .
				  "usr = ?, " .
				  "due = NULL " .
				  "WHERE isbn = ? AND " .
				  "cpy = ?");
	$query->bind_param(1, $user);
	$query->bind_param(2, $isbn);
	$query->bind_param(3, $copy);
	$query->execute();
	$query->finish();

	chomp(my $me = `whoami`);
	$query = $dbh->prepare("INSERT INTO log VALUES " .
			       "(?, ?, ?, CURRENT_TIMESTAMP, ?)");
	$query->bind_param(1, $user);
	$query->bind_param(2, "Checked Out(LAB)");
	$query->bind_param(3, $munged_isbn);
	$query->bind_param(4, $me);
	$query->execute();
	$query->finish();

        $self->{main_window}->unselect_all();
	
	$self->{main_window}->getbooks();
	$self->{main_window}->getcds();
	$self->{main_window}->getlaptops();
	$self->{main_window}->getkeys();

    }
    elsif ($function eq "admonish")
    {
	my $query = $dbh->prepare("DELETE FROM recall " .
				  "WHERE username = ?");
	$query->bind_param(1, $user);
	$query->execute();
	$query->finish();
	User_Window->run("admonish-1",
	                $user,
		        "Reason for admonish:");
    }
    elsif ($function eq "admonish-1")
    {
	my $query = $dbh->prepare("INSERT INTO admonish " .
				  "VALUES (?, ?)");
	$query->bind_param(1, $isbn);
	$query->bind_param(2, $user);
	$query->execute();
	$query->finish();
    }
    elsif ($function eq "unadmonish")
    {
	my $query = $dbh->prepare("DELETE FROM admonish " .
				  "WHERE username = ?");
	$query->bind_param(1, $user);
	$query->execute();
	$query->finish();
    }
    elsif ($function eq "recall")
    {
	my $query = $dbh->prepare("INSERT INTO recall " .
				  "VALUES (?, ?, NULL)");
	$query->bind_param(1, $user);
	$query->bind_param(2, $isbn);
	$query->execute();
	$query->finish();
    }

    $dbh->disconnect();
    $self->wgt('user_window')->destroy();
}

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

    $self->wgt('user_window')->destroy();
}

sub on_user_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 do_scan
{
    my ($self) = @_;

    my $user_entry = $self->wgt('user_entry');
    $user_entry->set_text($USER) if ($USER && $user_entry);

    1;
}

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

    return $self->{xml}->get_widget($widget);
}

1;

