#!/usr/local/bin/perl -w
#
# This software has been created by Genome Research Limited (GRL). 
# GRL hereby grants permission to use, copy, modify and distribute 
# this software and its documentation for non-commercial purposes 
# without fee at the user's own risk on the basis set out below.
# GRL neither undertakes nor accepts any duty whether contractual or 
# otherwise in connection with the software, its use or the use of 
# any derivative, and makes no representations or warranties, express
# or implied, concerning the software, its suitability, fitness for
# a particular purpose or non-infringement.
# In no event shall the authors of the software or GRL be responsible 
# or liable for any loss or damage whatsoever arising in any way 
# directly or indirectly out of the use of this software or its 
# derivatives, even if advised of the possibility of such damage.
# Our software can be freely distributed under the conditions set out 
# above, and must contain this copyright notice.
#
# $Id: penguin_ScanInOut.pl,v 1.1 2001/11/28 15:55:24 holroyd Exp $
#
# $Log: penguin_ScanInOut.pl,v $
% Revision 1.1  2001/11/28  15:55:24  holroyd
% Initial revision
%
#

BEGIN {
    unshift(@INC, "$ENV{'BADGER'}/bin");
    unshift(@INC, "."); 
}

use strict;
use Tk;
use Tk::ROText;
use Barcodelive;
use lib "/nfs/europa2/holroyd/badger-bin/penguin_new/modules/";
use lib "/nfs/europa2/holroyd/badger-bin";
use Penguin_FrontEnd;
use Penguin_Tools;
use sql_engine;

my $progname = "Scan In/Out";
my ( $win, $scan );

my $mw = new MainWindow;

$mw -> wm( 'minsize', 800,500 );
$mw -> wm( 'maxsize', 800,500 );
$mw->configure( -title => $progname );

my $frontEnd   = Penguin_FrontEnd->new( $progname, $mw );

$frontEnd->{version} = '1.0(beta)';

###################
# Load and prepare all sql statements from FreezerStorage.sql_lib
###################

my $STATEMENTS = statements->new( "gull" );
$STATEMENTS->default_sql_lib_path( "/nfs/europa2/holroyd/badger-bin/");
#$STATEMENTS->available_sql_libs("show_sql");
$STATEMENTS->load_sql_lib( ["FreezerStorage.sql_lib::all"]);

###################
# Create the array hash list of button specs to pass
# to penguin_FrontEnd.
###################

my $bttns = 	[
				{	
					text		=> 'Exit',					
					width	=> 8,
					
				},
				{
					text		=> 'Print Log',
					width	=> 8,
				},
				{
					text		=> 'Done',
					width	=> 8,
				},
				{
					text		=> 'Clear',
					width	=> 8,
				},
			];




$frontEnd->createBackground( $bttns );

#####################
# Put something in the main window
#####################

my @f = ( 120,150,300 );
my @l = ( 'freezer','entity' );



$frontEnd->{main}->configure( -bg => '#4682b4' );

	my $c=0;
	my $pad=0;
	$scan->{ScannedCount}=0;
	
	#####################
	# Create the main frames - [ left | middle | right ].
	#####################
	
	foreach my $frame ( qw( left middle right )) {
	$pad=4 if $c == 2;
	$win->{frames}{$frame} = 
			$frontEnd->{main}->Frame(#-relief 		=> 'ridge',
								#-borderwidth 	=> 2,
								-width 		=> $f[$c],
								-bg			=> '#4682b4',
								)->pack( 	-side => 'left',
										-fill => 'y',
										-padx => $pad,
										-pady => $pad, );
	
	$c++;									
}

	#########################################
	# Entry Labels
	#########################################
	$win->{frames}{left}->Label( -text => "Scan in freezer", -bg => '#4682b4' )->pack(-pady => 7 );
	$win->{frames}{left}->Label( -text => "Scan in entity", -bg => '#4682b4' )->pack(-pady => 7 );
	$win->{frames}{left}->Label( -bg => '#4682b4' )->pack(-pady => 7 );
	
	
	
	$win->{entries}{freezer} =
		$win->{frames}{middle}->Entry( -textvariable => \$scan->{input}{freezer} )->pack( -pady => 5 );
	$win->{entries}{entity} =
		$win->{frames}{middle}->Entry( -textvariable => \$scan->{input}{entity} )->pack( -pady => 5 );
	
	#########################################
	# Requestable button
	#########################################
	my $requestable = 'Requestable';
	$win->{bttns}{request} =
		$win->{frames}{middle}->Button( 	-text 			=> $requestable, 
									-width 			=> 17,
									-bg 				=> '#4682b4', 
									-activebackground 	=> '#6495ed',
									-fg 				=> 'blue', 
									-activeforeground	=> 'blue',
									-command 			=> sub 	{ 
																if( $requestable eq 'Requestable' ) {
																	$requestable = 'Non-Requestable';
																	$win->{bttns}{request}->configure( -text => $requestable, -fg => 'red', -activeforeground => 'red'  );
																}else{
																	$requestable = 'Requestable',
																	$win->{bttns}{request}->configure( -text => $requestable, -fg => 'blue', -activeforeground => 'blue'  );
																}
															}
								)->pack( -pady => 5 );
								
	
	$win->{frames}{middle}->Entry( -width => 4, -textvariable => \$scan->{PlateNumber} )->pack( -side => 'bottom', -pady => 4 );
	$win->{frames}{middle}->Label( -text => "Highlighted Plate Number", -bg => '#4682b4' )->pack( -side => 'bottom' );	
	
	$win->{frames}{middle}->Entry( -width => 4, -textvariable => \$scan->{ScannedCount} )->pack( -side => 'bottom', -pady => 4 );
	$win->{frames}{middle}->Label( -text => "No Scanned Entities", -bg => '#4682b4' )->pack( -side => 'bottom' );
	
	
	
	$win->{ROTextbox} =
		$win->{frames}{right}->Scrolled( "ROText", -height => 50, -width => 100, -scrollbars => 'e', -selectforeground => 'red' )->pack();



####################
# Focus on the Freezer widget and create the binds.
# Most of the hard work done here!
####################

$win->{entries}{freezer}->focus();

$win->{entries}{freezer}->bind( '<Return>', sub 	{ 	if( $scan->{input}{freezer} ) {
												my $refToHash = Barcodelive::Verifynumber( $scan->{input}{freezer} );
												if( $refToHash->{Process} eq 'Good' && $refToHash->{Type} eq 'FZ' ) {
													my $ref = $STATEMENTS->get( 'FreezerStorage.sql_lib::FreezerName', [ $refToHash->{Number} ]);	
													$scan->{InputFreezer} = $ref->[0][0];
													$scan->{input}{freezer} = $scan->{InputFreezer};
													$frontEnd->updateListBox( "Using freezer '$scan->{InputFreezer}'" );
													$win->{entries}{entity}->focus();
												}else{
													$frontEnd->updateListBox( "Unrecognised freezer" );
													$scan->{input}{freezer} = undef;
													return(0);
												}
											}
										});
$win->{entries}{entity}->bind(  '<Return>', sub 	{ 	
											if( !$scan->{input}{freezer} ) {
												$frontEnd->updateListBox( "Please scan a freezer" );
												$scan->{input}{entity} = undef;
											}else{
												$scan->{ScannedCount}++;
												&addPlate( $scan->{input}{entity} );
												$scan->{input}{entity} = undef;
											}
										} );
$win->{ROTextbox}->bind( '<Button-1>', 		sub 	{ $scan->{PlateNumber} = $scan->{plates}{$win->{ROTextbox}->getSelected()}->[0]; } );
#$win->{ROTextbox}->bind( '<Double-Button-1>', 	sub 	{ print STDERR "This will remove the plate from the scanned-in list!\n"; } );
$win->{ROTextbox}->bind( '<Double-Button-1>', 	sub 	{ 	
											my $entity = $win->{ROTextbox}->getSelected();
											$frontEnd->updateListBox( "Showing information for '$entity'" );
											Penguin_Tools:Entity->showEntityInfo( $scan->{plates}{$entity}->[2] ); 
										} );		

#####################
# Set button commands
#####################

$frontEnd->{bttns}{Exit}->configure(  		-command => sub 	{ 	$mw->destroy(); 			} );			
$frontEnd->{bttns}{Done}->configure(  		-command => sub 	{ 	$mw->destroy(); 			} );
$frontEnd->{bttns}{Clear}->configure( 		-command => sub 	{ 	&clearAll();    			} );
$frontEnd->{bttns}{"Print Log"}->configure( 	-command => sub   	{	&Penguin_Tools::printLog( $frontEnd ); 	} );
											
MainLoop;


sub addPlate {
	my $plate = shift;
	
	my $platename;
	
	my $refToHash = Barcodelive::Verifynumber( $plate );
	
	if( $refToHash->{Process} ne 'Good' ) {
		$frontEnd->updateListBox( "Plate number $scan->{ScannedCount} is not recognised" );
		return();
	}
	if( exists( $scan->{plates}{$refToHash->{Whole}} )) {
		$frontEnd->updateListBox( "Plate '$refToHash->{Whole}' already scanned - number $scan->{plates}{$refToHash->{Whole}}->[0]'" );
		return();
	}
	
	#while( my( $key,$val )=each( %{$refToHash} )) {
	#	print STDERR "$key -> $val\n";	
	#}
	
	push @{$scan->{plates}{$refToHash->{Whole}}}, $scan->{ScannedCount}, $requestable, $refToHash;
	
	my $textColor;
	if( $requestable eq 'Requestable' ) {
		$win->{ROTextbox}->tagConfigure( $refToHash->{Whole}, -foreground => 'blue' );	
	}else{
		$win->{ROTextbox}->tagConfigure( $refToHash->{Whole}, -foreground => 'red' );
	}
	
	$win->{ROTextbox}->insert( 'end', "$refToHash->{Whole}\n", $refToHash->{Whole} );
	$win->{ROTextbox}->update( 'idletasks' );
	
	return( 1 );
}

sub clearAll {
	
	$scan->{input}{freezer} = undef;
	$scan->{input}{entity}  = undef;
	$scan->{ScannedCount}   = 0;
	$scan->{plates}         = undef;
	$win->{ROTextbox}->delete( 1.0,'end' );
	
	$win->{entries}{freezer}->focus();
	
	$frontEnd->updateListBox( "Everything cleared!" );	
}


END {
	$STATEMENTS->end if $STATEMENTS;
};
