package APE::OutputControllerFactory::ConcreteOutputController::DefaultExoApeOutputController;

use base 'APE::OutputControllerFactory::ConcreteOutputController::DefaultOutputController';

$APE::OutputControllerFactory::ConcreteOutputController::DefaultExoApeOutputController::VERSION = '0.6';

use strict;
use warnings;
use Carp;
use Class::Throwable;
use SIBarcode;

use constant TRUE  => 1;
use constant FALSE => 0;

{
    my %_attributes = ();

    my %object;

    ## Autoloader wannabe. Inserts the sub calls that I want to be
    ## accessible into the symbol table.
    foreach my $attName (keys(%_attributes)) {
	no strict 'refs';
	*{__PACKAGE__ . "::get\u$attName"} = sub { $object{ $_[0] }->{$attName} }
    }


    #################################################################
    ## Initialise the objects private attributes. The argument is
    ## deleted as it is found, initialised and set.
    #################################################################
    sub _init {
	my ($self,%args) = @_;

	## Set attributes to passed values if present.
	foreach my $attName (keys(%args)) {
	    if(exists($_attributes{$attName})) {
		$object{ $self }->{$attName} = delete $args{$attName};
	    }
	}

	## Push the default options so that they are advertised for
	## use by the class user as output methods.
	$self->pushOption('Print Barcode' => \&_printBarcode);

	return $self->SUPER::_init(%args);
    }

    
    #################################################################
    ## Method to print a single barcode that represents this
    ## OutputController objects Result object. This is the default
    ## action for most Result objects.  This method may be called as
    ## part of the output method or as a single component of a
    ## specialised OutputController class that has used this class as
    ## its base class.
    #################################################################
    sub _printBarcode {
	my ($self,$results) = @_;
	my $flushController = ${$results->[0]->getFlushController};
	my $userObject      = ${$flushController->getUserObj};
	my $team            = $userObject->getWorkingTeam;
	my $bcPrinter       = $team->getDefaultBarcodePrinter;
	## We need a barcode printer to print barcodes!
	throw Class::Throwable::Simple("Error: barcode printer has not been set.") 
	    unless $bcPrinter->hasData;
	my $barcode = new Barcode(-Printer     => $bcPrinter->getName,
				  -Owner       => $userObject->getEmail,
				  #-NoOracle    => 1,
				  #-Override    => 1,
				  -FooterLabel => 0,
				  -HeaderLabel => 1);
	
	## Add a new label for each of the Result objects.
	foreach my $result (@{$results}) {
	    $barcode->addLabel(%{$result->getDescription});
	}
	## Print the labels or throw an exception.
	eval  { $barcode->printLabels; };
	if($@){ throw Class::Throwable::Simple("Error: problems printing result barcodes: $@"); }
    }
}


1;
