#!/usr/local/bin/perl 
#######################################################################
# 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: owl_get_maps2.pm,v 1.1 2002/08/16 10:45:13 kva Exp $

require Exporter;

@owl_get_maps::ISA = qw(Exporter);
@owl_get_maps::EXPORT = qw(get_maps create_printmap_struct);

package owl_get_maps2;

# DN1
################################################################################
#Interrogate the database for maps of 'created' samples for the correct view   #
################################################################################
# Supply                 $dbh                             -> database connection
# Supply                 $time                            -> the time-band for the query
# Supply                 $ID_TEAM_FINSERV                 -> the finishing-service in question
# Supply                 $fsname                          -> description from above
# Supply                 $who                             -> the current operator
# Supply                 $mode                            -> currently Created or Printed

sub get_maps {
    
    my ($dbh, $time, $ID_TEAM_FINSERV, $fsname, $who, $mode) = @_;
    #warn "$time, $ID_TEAM_FINSERV, $fsname, $who, $mode\n";
    my @RETURNMAPS = ();

# limited options for the moment
    if ($time ne 'all'){
	$time = 'all';
    }
    #warn "*LIMITED* We want maps from ---> $time for $fsname operator is $who\n";


    # Note that $fsname will be either eg. 'trillion' or 'Private samples'
    # If it is 'Private samples' we will require Operator to get at the maps
    my $statement;
    ###########################################################
    # Grab Created-maps
    ###########################################################

    ###########
    # New code
    ###########
    if ($mode eq 'Robot assigned') {
	$statement = "
select mapplate.ID_MAPPLATE, mapplate.PLATE_FORMAT, mapplate.ID_RUNTYPE, mapplate.PROTOCOL
from mapplate, mapplate_status
where mapplate.id_mapplate = mapplate_status.id_mapplate
and mapplate_status.status = 5
and mapplate_status.iscurrent = 1
and mapplate.ID_TEAM_FINSERV = \'$ID_TEAM_FINSERV\'
";
    }
    # 
    ###########
    

    elsif ($mode eq 'Created') {
	if ($fsname ne 'private finisher'){
	    $statement = "
select mapplate.ID_MAPPLATE, mapplate.PLATE_FORMAT, mapplate.ID_RUNTYPE, mapplate.PROTOCOL
from mapplate, mapplate_status
where mapplate.id_mapplate = mapplate_status.id_mapplate
and mapplate_status.status in (1, 5)
and mapplate_status.iscurrent = 1
and mapplate.ID_TEAM_FINSERV = \'$ID_TEAM_FINSERV\'
";
	} else {
	    $statement = "
select mapplate.ID_MAPPLATE, mapplate.PLATE_FORMAT, mapplate.ID_RUNTYPE, mapplate.PROTOCOL
from mapplate, mapplate_status
where mapplate.id_mapplate = mapplate_status.id_mapplate
and  mapplate_status.status in (1, 5)
and mapplate_status.iscurrent = 1
and mapplate.ID_TEAM_FINSERV = \'$ID_TEAM_FINSERV\'
and mapplate_status.operator = \'$who\'
";
	}
    }
    
    ###########################################################
    # Grab Created-maps
    ###########################################################
    elsif ($mode eq 'Printed') {
	if ($fsname ne 'private finisher'){
	    $statement = "
select mapplate.ID_MAPPLATE, mapplate.PLATE_FORMAT, mapplate.ID_RUNTYPE, mapplate.PROTOCOL
from mapplate, mapplate_status
where mapplate.id_mapplate = mapplate_status.id_mapplate
and mapplate_status.status in (2, 7)
and mapplate_status.iscurrent = 1
and mapplate.ID_TEAM_FINSERV = \'$ID_TEAM_FINSERV\'
";
	} else {
	    $statement = "
select mapplate.ID_MAPPLATE, mapplate.PLATE_FORMAT, mapplate.ID_RUNTYPE, mapplate.PROTOCOL
from mapplate, mapplate_status
where mapplate.id_mapplate = mapplate_status.id_mapplate
and  mapplate_status.status in (2, 7)
and mapplate_status.iscurrent = 1
and mapplate.ID_TEAM_FINSERV = \'$ID_TEAM_FINSERV\'
and mapplate_status.operator = \'$who\'
";
	}
    }

    #warn "MODE -> $mode \n";
    #warn "STATE -> $statement \n";


    my $sth = $dbh->prepare($statement) || die "ERROR:$DBI::errstr";
    $sth->execute || die "ERROR:$DBI::errstr";
    my ($ID_MAPPLATE, $PLATE_FORMAT, $ID_RUNTYPE, $PROTOCOL);
    while (($ID_MAPPLATE, $PLATE_FORMAT, $ID_RUNTYPE, $PROTOCOL) = $sth->fetchrow()){
	if ($ID_RUNTYPE eq ''){
	    $ID_RUNTYPE = 'NULL';
	}

	
	##############################################################################
	# For each of the maps which we grab from the database; it would be useful to 
	# also have the date of CREATION and the PLATE_FORMAT
	##############################################################################

	if ($mode eq 'Created'){
	    $statement_d = "
select mapplate_status.STATUSDATE, mapplate.PLATE_FORMAT
from mapplate_status, mapplate 
where mapplate_status.id_mapplate = mapplate.id_mapplate
and mapplate_status.ID_MAPPLATE = \'$ID_MAPPLATE\'
and mapplate_status.STATUS  = 1
and mapplate_status.ISCURRENT = 1
";
	}

	elsif ($mode eq 'Printed'){
	    $statement_d = "
select mapplate_status.STATUSDATE, mapplate.PLATE_FORMAT
from mapplate_status, mapplate 
where mapplate_status.id_mapplate = mapplate.id_mapplate
and mapplate_status.ID_MAPPLATE = \'$ID_MAPPLATE\'
and mapplate_status.STATUS  in (2, 7)
and mapplate_status.ISCURRENT = 1
";
	}	
	
	elsif ($mode eq 'Robot assigned'){
	    $statement_d = "
select mapplate_status.STATUSDATE, mapplate.PLATE_FORMAT
from mapplate_status, mapplate 
where mapplate_status.id_mapplate = mapplate.id_mapplate
and mapplate_status.ID_MAPPLATE = \'$ID_MAPPLATE\'
and mapplate_status.STATUS  = 5
and mapplate_status.ISCURRENT = 1
";
	}


	#warn "THIS ONE !$statement_d \n";


########################################################################### 


	$sth_d = $dbh->prepare($statement_d) || die "ERROR:$DBI::errstr";
	$sth_d->execute || die "ERROR:$DBI::errstr";
	my ($STATUSDATE, $PLATE_FORMAT) = $sth_d->fetchrow();
	$sth_d->finish;

	my $map = "$ID_MAPPLATE" . "_" . "$PROTOCOL" . "$ID_RUNTYPE" . " " . "commited $STATUSDATE". " " . "$PLATE_FORMAT well";

	#my $map = "$ID_MAPPLATE" . "_" . "$PROTOCOL" . "$ID_RUNTYPE";
	push @RETURNMAPS, $map;

    }
    $sth->finish;
    
    # Return our list of maps
    return(@RETURNMAPS);

}

# DN1
###################################################################
# get these maps into a data-structure suitable for owl_printmaps #
###################################################################
# Supply                 $dbh                             -> database connection
# Supply                 @map_select_blocks               -> the list of maps to look at
# Supply                 
# Supply                 

sub create_printmap_struct {
    #warn "inside create_printmap_struct \n";
    my ($dbh, @map_select_blocks) = @_;
    my $map;
    my @printmap_struct = ();

    my $this_block_count;
    my $last_block;
    my $this_block;
    my $from_MAPROW;
    my $from_MAPCOL;

    my @array_array2 = ();

    #################################### 
    # Go through all the selected-maps #
    ####################################
    foreach $map (@map_select_blocks){
	$last_block = 'None';
	$this_block = 'First-block';
	#my ($MAPROW, $MAPCOL)
	$from_MAPROW = 'a';
	$from_MAPCOL = '1';

	my $sample_count = 1; 
	
	$this_block_count = 0;

	my @array_array = ();
	my @array = ();

	my ($ID_MAPPLATE, $PROTOCOL, $ID_RUNTYPE);
	# split $map (eg. 281_Q1CNULL) up into ID_MAPPLATE PROTOCOL ID_RUNTYPE 
	#warn "map ----> $map\n";
	if ($map =~ /^(\d+)_(\w+)\s+/){
	    $ID_MAPPLATE = $1;
	} else {
	    warn "Something is wrong ! \n";
	}


	$PROTOCOL = substr $2, 0, 3;
	$ID_RUNTYPE = substr $2, 3;
	
	####################################################
	# Find out the total number of samples on this map #
	####################################################
	$statement = "
select count (id_frequest)
from request_map
where ID_MAPPLATE = \'$ID_MAPPLATE\'
";
	$sth = $dbh->prepare($statement) || die "ERROR:$DBI::errstr";
	$sth->execute || die "ERROR:$DBI::errstr";
	my $total = $sth->fetchrow();
	$sth->finish;

	#warn "TOTAL THIS PLATE IS -> $total \n";
	
	#############################
	# Find out the plate-format #
	#############################
	my $statement = "
select PLATE_FORMAT from mapplate
where ID_MAPPLATE = \'$ID_MAPPLATE\'
";
	my $sth = $dbh->prepare($statement) || die "ERROR:$DBI::errstr";
	$sth->execute || die "ERROR:$DBI::errstr";
	my $PLATE_FORMAT = $sth->fetchrow();
	$sth->finish;


	
	my @mapinfo = ();

	##################################################
	# Go through the individual-entries for this map #
	##################################################
	$statement = "
select ID_FREQUEST, ID_MAP
from request_map
where ID_MAPPLATE = \'$ID_MAPPLATE\'
order by ID_MAP
";
	$sth = $dbh->prepare($statement) || die "ERROR:$DBI::errstr";
	$sth->execute || die "ERROR:$DBI::errstr";
	while (($ID_FREQUEST, $ID_MAP) = $sth->fetchrow()){
	    
	    ####################################
	    # Find out row-col for this sample #
	    ####################################
	    $statement2 = "
select MAPROW, MAPCOL
from rowcol_map
where ID_MAP = \'$ID_MAP\'
";
	    $sth2 = $dbh->prepare($statement2) || die "ERROR:$DBI::errstr";
	    $sth2->execute || die "ERROR:$DBI::errstr";
	    ($MAPROW, $MAPCOL) = $sth2->fetchrow();
	    $sth2->finish;

	    #warn "_ID_FREQUEST $ID_FREQUEST _ID_MAP $ID_MAP _MAPROW $MAPROW _MAPCOL $MAPCOL";

	    #######################################
	    # Some new code here >!<
	    my @orders;
	    push @orders, $ID_FREQUEST;
	    push @orders, $MAPROW;
	    push @orders, $MAPCOL;
	    push @array_array2, [@orders];
	    #
	    #######################################


	    ############################################################# 
	    # Work out a blockname for this sample(projectname_finisher #
            #############################################################
	    # what project is this sample from >?<
	    $statement3 = "
select finish_batch.projectname 
from finish_batch, finish_request
where finish_batch.id_fbatch = finish_request.id_fbatch
and finish_request.id_frequest = \'$ID_FREQUEST\'
";
	    $sth3 = $dbh->prepare($statement3) || die "ERROR:$DBI::errstr";
	    $sth3->execute || die "ERROR:$DBI::errstr";
	    ($PROJECTNAME) = $sth3->fetchrow();
	    $sth3->finish;
	
	    # what finisher is this request from >?<
	    $statement4 = "
select person.email
from person, team_person_role, finish_batch, finish_request
where finish_batch.id_fbatch = finish_request.id_fbatch
and finish_batch.finisher = team_person_role.id_role
and team_person_role.id_person = person.id_person
and finish_request.id_frequest = \'$ID_FREQUEST\'
";
	    $sth4 = $dbh->prepare($statement4) || die "ERROR:$DBI::errstr";
	    $sth4->execute || die "ERROR:$DBI::errstr";
	    ($EMAIL) = $sth4->fetchrow();
	    $sth4->finish;

	    #####################
	    $this_block = "$PROJECTNAME" . "_" . "$EMAIL";
	    if ($sample_count == 1){
		$last_block = $this_block;
	    }
	    $sample_count++;
	    
	    $this_block_count++;
	    #####################


	    #warn "DEBUG  ->  this_block $this_block last_block $last_block \n";
	    #warn "DEBUG2 ->  sample_count $sample_count total $total \n";
	    #warn "DEBUG3 ->  this_block_count $this_block_count \n";

	    #######################################
            # Code to populate our data-structure #
	    #######################################
	    if (($this_block ne $last_block) || ($sample_count > $total)){

		#ie. we have changed to a new block
		# by this point we should know all we need to
		# go into @array

		#warn "*************************ENTERING DATA INTO ARRAY******************\n";

		# Note; if $this_block ne $last_block is TRUE $MAPROW and $MAPCOL should be 1 coordinate less
		my $coordinates;
		if ($this_block ne $last_block){
		    
		    ##############
		    $this_block_count--;
		    ##############

		    my $new_ID_MAP = ($ID_MAP-1);
		    # work out new row-col values from $new_ID_MAP
		    my ($new_MAPROW, $new_MAPCOL);
		    $statementn = "
select MAPROW, MAPCOL
from rowcol_map
where ID_MAP = \'$new_ID_MAP\'
";
		    $sthn = $dbh->prepare($statementn) || die "ERROR:$DBI::errstr";
		    $sthn->execute || die "ERROR:$DBI::errstr";
		    ($new_MAPROW, $new_MAPCOL) = $sthn->fetchrow();
		    $sthn->finish;
		    $coordinates = "$from_MAPROW" . "$from_MAPCOL" . "-" . "$new_MAPROW" . "$new_MAPCOL";

		    push @array, $coordinates;
		    push @array, $last_block;
		    push @array, 1;
		    push @array, $this_block_count;

		    push @array_array, [@array]; #####
		    @array = ();
		    $this_block_count = 1;
		    
		} else {

		    $coordinates = "$from_MAPROW" . "$from_MAPCOL" . "-" . "$MAPROW" . "$MAPCOL";
		
		    push @array, $coordinates;
		    push @array, $last_block;
		    push @array, 1;
		    push @array, $this_block_count;
		    push @array_array, [@array]; #####
		    @array = ();
		    
		}
	       
		# We need to remember the start-coordinates for the new-block
		$from_MAPROW = $MAPROW;
		$from_MAPCOL = $MAPCOL;

	    }
	    #warn "changing last_block to this_block -> $this_block\n"; 
	    $last_block = $this_block;

	} # matches while...

	# TRAP A NASTY EVENT
	if (($this_block_count) == 1 && ($total != 1)){
	    # we have missed a block on the end of a map containing 1 sample
	    # ARG ! unless this map contains only 1 block, containing 1 sample

	    #warn "EVENT TRAPPED !!!! \n";
	    
	    $coordinates = "$from_MAPROW" . "$from_MAPCOL" . "-" . "$MAPROW" . "$MAPCOL";
	    # we have seen a new block
	    # we must record the rowcol for the old block
	    push @array, $coordinates;
	    push @array, $last_block;
	    push @array, 1;
	    push @array, $this_block_count;
	    push @array_array, [@array]; #####
	    @array = ();

	}

	$sth->finish;
    
	################################################
	#foreach map we need to create an entry in our #
	# datastructure; @printmap_struct              #
	################################################
	
	#warn "******************************************************\n";
	#warn "******************************************************\n";
	#my $capture = Data::Dumper::Dumper(@array_array);
	#warn $capture;


	my $comment = "$PROTOCOL" . "$ID_RUNTYPE";
	my $hash = {
	    "map_name" => "$ID_MAPPLATE", 
	    "format" => "$PLATE_FORMAT",
	    "comment" => "$comment",
	    "mapinfo" => [@array_array],

	    #####################################
	    #NEW#
	    "map_reads" => [@array_array2]
	    #####################################   

	    };

	@array_array2 = ();
	push @printmap_struct, $hash;
	
    } # end of foreach map 

    #warn "******************************************************\n";
    #warn "******************************************************\n";
    #my $capture = Data::Dumper::Dumper(@printmap_struct);
    #warn $capture;
    #die;

    return(@printmap_struct);
    

}
1;







