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

package Add_Window;
use strict;
our $ADD;
use CSL::Gnome2;
use Gnome2;
use Gtk2::GladeXML;
use CSL::DBs;
use Carp;
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",
                                'add_window');
    croak "Error opening Glade file" if (!$self->{xml});

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

    return $self;
}

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

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

    my $self = $class->new;
    $self->{main_window} = $main_window;

    $self->wgt('category_combo')->set_active(0);

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

    Gtk2->main();
    $main_window->getbooks();
    $main_window->getcds();
    $main_window->getlaptops();
    $main_window->getkeys();
}

sub on_ok_button_clicked
{
    my ($self) = @_;
    
    my $dbh = DBI->connect($CSL::DBs::csdb);
    $dbh->do("set search_path to library");

    my $isbn = $self->wgt('isbn_entry')->get_text();
    if (!$isbn)
    {
        Alert_Window->run("Please enter an ISBN.");
        return;
    }

    $isbn =~ s/-//g;
    $isbn =~ tr/a-z/A-Z/;
    my $copy = 0;
    if ($isbn =~ /^(.+)C(\d+)$/)
    {
	$isbn = $1;
	$copy = $2;
    }
    my $category = $self->wgt('category_combo')->get_active_text();
    $category =~ tr/A-Z/a-z/;
    
    my $query = $dbh->prepare("INSERT INTO books " .
			      "(isbn, cpy, cat, title, author, status) " .
			      "VALUES (?, ?, ?, ?, ?, 'Available')");
  
    $query->bind_param(1, $isbn);
    $query->bind_param(2, $copy);
    $query->bind_param(3, $category);
    $query->bind_param(4, $self->wgt('title_entry')->get_text());
    $query->bind_param(5, $self->wgt('author_entry')->get_text());
    $query->execute();
    $query->finish();
    $dbh->disconnect();

    $self->wgt('add_window')->destroy();
    $self->{main_window}->getbooks();
    $self->{main_window}->getcds();
    $self->{main_window}->getlaptops();
    $self->{main_window}->getkeys();
    $self->{main_window}->unselect_all();
}


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

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

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

    my $isbn_entry = $self->wgt('isbn_entry');
    $isbn_entry->set_text($ADD) if ($ADD && $isbn_entry);

    1;
}

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

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


1;

