package GTx::APE::InputController::COORD2PLATE_InputController;

use base 'GTx::APE::InputController';

use strict;
use warnings;
use Carp;

use GTx::APE::InputController::Requirement;
use GTx::APE::InputController::EPSA_InputController;

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) = @_;
	foreach my $attName (keys(%args)) {
	    if(exists($_attributes{$attName})) { 
		$object{ $self }->{$attName} = delete $args{$attName};
	    }
	} 

  	## Set the description as this is a specialised InputController.
	$args{description} = "An InputController that adds a Requirement object to " . 
	    "the requirementList. The new Requirement object is type 'Input' and " . 
	    "requires the user to enter a plate well coord.";
	
	return $self->SUPER::_init(%args);
    }


    #################################################################
    ## Overridden method from base class to create the Requirement
    ## objects. Calls the base class method of the same name to build
    ## the basic number of Requirement objects. It then adds its own
    ## Requirement object (type='Input') that requests the user to
    ## enter a plate coord.
    #################################################################
    sub createRequirements {
	my $self = shift;
	$self->SUPER::createRequirements();
	$self->pushRequirement
	    ( new GTx::APE::InputController::Requirement
	      (arrayingEntityIndex=> -1,
	       atomicProcessIndex => -1,
	       type               => 'Input',
	       description        => 'Enter well coord [rowcol]: ',
	       checkingCode       => qr/[a-h][1-12]$/ ) );	

	## The getData method requires an EPSA_InputController method.
	$object{ $self }->{epsaInputController} =
	    new GTx::APE::InputController::EPSA_InputController
	    (atomicProcessContainer=>$self->getAtomicProcessContainer(),
	     sqlEngineObj          =>$self->getSqlEngineObj());
    }


    #################################################################
    ## Overridden method from base class to create the Requirement
    ## objects. Calls the base class method of the same name to build
    ## the basic number of Requirement objects. It then adds its own
    ## Requirement object (type='Input') that requests the user to
    ## enter a plate coord.
    #################################################################
    sub process {
	my ($self,$requirementObj) = @_;
	if($self->isDuplicateData($requirementObj)) {
	    croak "ERROR: '",$requirementObj->getData(), "' has already been entered.\n";
	}
	## Get data associated with Requirement.
	## Ignore 'Input' type Requirement objects.
	unless($requirementObj->getType() eq 'Input') {
	    $requirementObj = eval  { $self->getData($requirementObj); };
	    if($@)                  { croak $@; }
	}
	## Push this Requirement onto the complete list.
	$self->pushCompletedRequirement($requirementObj);
	## Wait until all of the Requirement objects have been
	## returned.
	print STDERR "Testing: ",$self->getRequirementCount()." == ". 
	    $self->getCompletedRequirementCount()."\n";
	if($self->getRequirementCount() == $self->getCompletedRequirementCount()) {
	    $self->_alterArrayPatterns();
	    ## Set the sessionId foreach ArrayingEntity via the AtomicProcessContainer.
	    eval  { ${$self->getAtomicProcessContainer()}->setSessionId($self->getSessionId()); };
	    if($@){ croak "ERROR: can't set the sessionId: $@\n";                               }
	    foreach my $req (@{$self->getCompletedRequirementList()}) {
		## Call the generic data arraying method in the base
		## class.
		$self->arrayData($req);
	    }
	}
    }

    
    #################################################################
    ## Method to alter the array patterns in each of the AtomicProcess
    ## objects pointed to by each of the Requirement objects held in
    ## the completedRequirementsList so that they match the selected
    ## well of the source plate.
    #################################################################
    sub _alterArrayPatterns {
	my $self = shift;
	print STDERR "Altering ArrayPatterns.\n";
	my $inputRequirement = $self->popCompletedRequirement();
	my $coord            = $inputRequirement->getData();
	foreach my $requirementObj (@{$self->getCompletedRequirementList()}) { 
	    my $arrayingEntityIndex    = $requirementObj->getArrayingEntityIndex();
	    my $atomicProcessIndex     = $requirementObj->getAtomicProcessIndex();
	    my $atomicProcessContainer = ${$self->getAtomicProcessContainer()};
	    my $arrayingEntity         = $atomicProcessContainer->getArrayingEntityList()->[$arrayingEntityIndex];
	    my $atomicProcess          = $arrayingEntity->getAtomicProcessList()->[$atomicProcessIndex];
	    ## Fetch then delete the hash of ArrayPattern objects from the
	    ## AtomicProcess object.
	    my $arrayPatternHash  = $atomicProcess->deleteArrayPatternHash();
	    print STDERR "Deleted ArrayPatternHash: $arrayPatternHash\n";
	    ## Adjust the ArrayPattern object to show the new inMapId data.
	    foreach my $mapId (keys(%{$arrayPatternHash})) {
		foreach my $arrayPattern (@{$arrayPatternHash->{$mapId}}) {
		    eval  { $arrayPattern->_setInCoord($coord); };
		    if($@){ croak $@;                          }
		    $atomicProcess->addArrayPattern($arrayPattern);
		    print STDERR "New ArrayPattern: " .
			$arrayPattern->getInMapId() . " = " . 
			$arrayPattern->getInRow() . $arrayPattern->getInColumn() .
			"\n";
		}
	    }
	    print STDERR "New AtomicProcess ArrayPattern count: ", $atomicProcess->getArrayPatternCount(), "\n";
	}
    }


    
    #################################################################
    ## Overridden method from base class to get data associated with 
    ## less well known entity types. This method creates a new       
    ## EPSA_InputController and uses its getData method as it knows 
    ## how to distinquish between an EP sense and EP antisense entity
    ## and thus get the correct information from the database.
    #################################################################
    sub getData {
	my ($self,$requirementObj) = @_;

	my $completedRequirementObj = 
	    eval  { $object{ $self }->{epsaInputController}->getData($requirementObj); };
	if($@){ croak $@; }
	
	return $completedRequirementObj;
    }


    #################################################################
    ## Method to destroy this object.
    #################################################################
    sub DESTROY {
	my $self = shift;
	delete $object{$self};
	$self->SUPER::DESTROY;
    }
}

1;
