#!/usr/local/bin/perl5.004
# Contact: bug


# 
# Description; A module to give printouts of plate
#              submissions to the WP via the Booth.

#print STDERR "Using local version of platetrack_submitted !\n";

use strict;
use Carp;
use WrapDBI;
use SDTable;
use platetrack_general;

package platetrack_submitted;

require Exporter;
@platetrack_submitted::ISA = qw(Exporter);
@platetrack_submitted::EXPORT = qw(platetrack_submitted);

sub platetrack_submitted {

    #print STDOUT "Using local version of platetrack_submitted !!\n";

    my ($email, $list, $printer, $JIT) = @_;

    my $db = "reports";

    # Just give up now if the list is empty
    if (scalar @$list == 0){
	return("empty");
    }

    # Check the printer exists
    
    open(FH, "lpq -P$printer 2>&1 |");
    while (<FH>) {
	if ($_ =~ /unknown/){ Carp::croak "$printer: Unknown printer: $!";}
    }
    close (FH);

    # Find out team from $email
    my $dbh = my $dbh = WrapDBI->connect("$db", {RaiseError => 1});
    my $team = convert->email2teamname($dbh, $email);

    # Get the relevant data from our list of lp's
    if ($JIT == 0){undef $JIT;}
    my $data = get->wp_submit_data_from_lps($dbh, $list, $JIT);

    $dbh->disconnect();

    ###########
    # Printout
    ###########

    my $table = SDTable->new('format' => 'gaudy');
    $table->set('title' => "Loadingplate Submissions from $email (Team $team).");
    $table->set('titles' => ['Id_loadingplate','Platename','Date of WP arrival', 'Time', 'Type']);

    my ($ABI, $OTHER) = 0;
    foreach my $n ( sort numerically ( keys(%$data) ) ){
	$data->{$n} =~ /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/;
	my @values = ($n, $1, $2, $3, $4);
	if ($4 =~ /ABI/){
	    $ABI++;
	} elsif ($4 =~ /3700/){
	    $OTHER++;
	}
	$table->add(@values);
    }

    my $count = scalar @$list;

    open(OUTPUT,"| lpr -P$printer") || Carp::croak "$printer: Problems opening filehandle to printer: $!";
    print OUTPUT $table->format();
    print OUTPUT "Total submitted - $count\n";
    print OUTPUT "ABI - $ABI     3700 - $OTHER\n";

#    print STDOUT $table->format();
#    print STDOUT "Total submitted - $count\n";
#    print STDOUT "ABI - $ABI     3700 - $OTHER\n";

    close OUTPUT;

}

sub numerically { $a <=> $b; }

1;


