package SGN::View::Mason::Commands;
use strict;
use vars qw($m $c);
HTML::Mason::Component::FileBased->new(
'code' => sub {
use utf8; local $SGN::View::Mason::Commands::m = $HTML::Mason::Commands::m;
HTML::Mason::Exception::Params->throw
    ( error =>
      "Odd number of parameters passed to component expecting name/value pairs"
    ) if @_ % 2;
my ( $marker );
{
    my %pos;
    for ( my $x = 0; $x < @_; $x += 2 )
    {
        $pos{ $_[$x] } = $x + 1;
    }

    foreach my $arg ( qw( marker ) )
    {
        HTML::Mason::Exception::Params->throw
            ( error => "no value sent for required parameter '$arg'" )
                unless exists $pos{$arg};
    }
#line 29 "/home/production/cxgn/sgn/mason/markers/locations.mas"
    $marker = $_[ $pos{'marker'} ];
}
$m->debug_hook( $m->current_comp->path ) if ( HTML::Mason::Compiler::IN_PERL_DB() );

#line 27 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print( '
' );
#line 31 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print( '
' );
#line 32 "/home/production/cxgn/sgn/mason/markers/locations.mas"

use CXGN::Cview::MapFactory;
use CXGN::Cview::ChrMarkerImage;

my $locations_html = '';
my $marker_name    = $marker->get_name();
my @displayed_locs;
my @displayed_pcr;

#if we have some experiments, and they are an arrayref, and there is at least one location in them
my $experiments = $marker->current_mapping_experiments() || [];

if (    $experiments
    and @{$experiments}
    and grep { $_->{location} } @{$experiments} )
{
    my $count = 1;
    for my $experiment ( @{$experiments} ) {

#make sure we have a location before we go about showing location data--some experiments do not have locations
        if ( my $loc = $experiment->{location} ) {

#make sure we haven't displayed a location entry with the same location ID already
            unless ( grep { $_ == $loc->location_id() } @displayed_locs ) {
                push( @displayed_locs, $loc->location_id() );
                if ( $count > 1 ) {
                    $locations_html .= '<br />';
                }
                $locations_html .=
'<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr>';

                #make a section detailing the location
                my $protocol = '';
                my $pcr      = $experiment->{pcr_experiment};
                my $rflp     = $experiment->{rflp_experiment};
                $protocol = $experiment->{protocol};
                unless ($protocol) {
                    if ($pcr) {
                        $protocol = 'PCR';
                    }
                    elsif ($rflp) {
                        $protocol = 'RFLP';
                    }
                    else {
                        $protocol = '<span class="ghosted">Unknown</span>';
                    }
                }

                #make a link to the map this marker can be found on
                my $map_version_id = $loc->map_version_id();
                my $lg_name        = $loc->lg_name();
                my $position       = $loc->position();
                my $subscript      = $loc->subscript();
                $subscript ||= '';
                my $map_url = '';
                my $map_id  = '';

                my $dbh         = $marker->{dbh};
                my $map_factory = CXGN::Cview::MapFactory->new($dbh);
                my $map =
                  $map_factory->create( { map_version_id => $map_version_id } );
		if (!$map) {
		  print "map_version_id = $map_version_id could not be instantiated\n"; 
		  next;
		}
                my $map_name = $map->get_short_name();
                if ($map_version_id) {
                    $map_id = $map->get_id();

                    if (    $map_id
                        and $map_name
                        and defined($lg_name)
                        and defined($position) )
                    {
                        $map_url =
"<a href=\"/cview/view_chromosome.pl?map_version_id=$map_version_id&amp;chr_nr=$lg_name&amp;cM=$position&amp;hilite=$marker_name$subscript&amp;zoom=1\">$map_name</a>";
                    }
                }
                else {
                    $map_url =
                      '<span class="ghosted">Map data not available</span>';
                }
                my $multicol = 1;
                my $width    = "300px";
                if ( $subscript and $multicol > 1 ) { $multicol++; }
                my @locations = (
                    '__title' =>
"<b>Map:</b> $map_url&nbsp;&nbsp;&nbsp;",
                    '__tableattrs' => "width=\"$width\"",
                    '__multicol'   => $multicol,
		    'Map version'  => $map_version_id." (location: ".$loc->location_id().")",
		    'Chromosome'   => $loc->lg_name(),
                    'Position    ' => sprintf( '%.2f', $loc->position() )." ".$map->get_units(),
                    'Confidence'   => $loc->confidence(),
                    'Protocol'     => $protocol
                );
                if ($subscript) {
                    push( @locations, ( 'Subscript' => $subscript ) );
                }
                $locations_html .= '<td width = "25%">';
                $locations_html .=
                  CXGN::Page::FormattingHelpers::info_table_html(@locations);
                $locations_html .= '</td>';
                $locations_html .= '<td align="center">';
                ####$map_factory = CXGN::Cview::MapFactory->new($dbh);
#######	my $map=$map_factory->create({map_version_id=>$map_version_id});
#######	my $map_version_id=$map->get_id();

                my $hilite_name = $marker_name;
                if ($subscript) {
                    $hilite_name .= $subscript;
                }
                my $chromosome = CXGN::Cview::ChrMarkerImage->new(
                     "", 240, 150, $dbh, $lg_name, $map, $hilite_name,
                     $c->get_conf("basepath"),  $c->get_conf('tempfiles_subdir')."/cview",
                 );
                my ( $image_path, $image_url ) =
                  $chromosome->get_image_filename();
                my $chr_link =
qq|<img src="$image_url" usemap="#map$count" border="0" alt="" />|;
                $chr_link .= $chromosome->get_image_map("map$count");
                $chr_link .= '<br />' . $map_name;
                $count++;
                $locations_html .= '<br />';
                $locations_html .= $chr_link;
                $locations_html .= '</td></tr></table>';


#if we have a pcr experiment that was used to map this marker to this location, make a section for this experiment's data
                if ( $pcr
		     and !grep { $_ == $pcr->pcr_experiment_id() }
		     @displayed_pcr )
		  {
                    $locations_html .=
		      '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr>';
                    my $pcr_bands    = $pcr->pcr_bands_hash_of_strings();

		    my %pcr_bands_by_name = ();
		    my $sth = $dbh->prepare("SELECT organism.species || ' ' ||  stock.name FROM public.stock JOIN public.organism USING(organism_id) WHERE stock_id=?");

		    foreach my $p (keys %$pcr_bands) { 

		      $sth->execute($p);
		      $pcr_bands_by_name{($sth->fetchrow_array)} = $pcr_bands->{$p};
		    }


                    my $digest_bands = $pcr->pcr_digest_bands_hash_of_strings();

		    my %pcr_digest_bands_by_name = ();
		    foreach my $p (keys %$digest_bands) { 
		      $sth->execute($p);
		      $pcr_digest_bands_by_name{($sth->fetchrow_array)} = $digest_bands->{$p};
		    }


                    my $pcr_bands_html =
                      CXGN::Page::FormattingHelpers::info_table_html(
								     __border => 0,
								     __sub    => 1,

								     %pcr_bands_by_name,
								    );
                    my $digest_bands_html =
                      CXGN::Page::FormattingHelpers::info_table_html(
								     __border => 0,
								     __sub    => 1,
								     %pcr_digest_bands_by_name,
								    );
                    my $mg = '';
                    if ( $pcr->mg_conc() ) {
		      $mg = $pcr->mg_conc() . 'mM';
                    }
                    my $temp = '';
                    if ( $pcr->temp() ) {
                        $temp = $pcr->temp() . '&deg;C';
                    }
                    $locations_html .= '<td>';
                    my $fwd = $pcr->fwd_primer()
                      || '<span class="ghosted">Unknown</span>';
                    my $rev = $pcr->rev_primer()
                      || '<span class="ghosted">Unknown</span>';
                    my $enz = $pcr->enzyme()  || 'unknown enzyme' ;
		    my $additional_enzymes = $pcr->additional_enzymes();
                    my $dcaps = $pcr->dcaps_primer();
                    $temp ||= '<span class="ghosted">Unknown</span>';
                    $mg   ||= '<span class="ghosted">Unknown</span>';
                    my $digest_title = "Digested band sizes (using $enz)";

                    unless ($digest_bands_html) {
                        $digest_title      = '&nbsp;';
                        $digest_bands_html = '&nbsp;';
                    }

                    ### TODO ###
                    my ( $dcaps_left, $dcaps_right );

                    if ($dcaps) {
                      $dcaps_left  = "dCAPS primer (5'-3')";
                      $dcaps_right = "<span class=\"sequence\">$dcaps</span>";
                    }
                    ###########
                    my $pcr_seq = $pcr->get_sequences;

                    my ($aspe, $aspe_primers);
                    $aspe_primers = join ('<BR>' ,  @{ $pcr_seq->{ASPE_primer} }  ) if  $pcr_seq->{ASPE_primer}  ;
                    if ($aspe_primers) {
                      $aspe = "ASPE primers (5'-3')";
                      $aspe_primers = "<span class=\"snp\">$aspe_primers</span>"
                    }
                    my ($snp, $snp_nuc);
                    $snp_nuc = join ('<BR>' ,  @{ $pcr_seq->{SNP} }  ) if  $pcr_seq->{SNP}  ;
                    if ($snp_nuc) {
                      $snp = "SNP nucleotide";
                      $snp_nuc = "<span class=\"snp\">$snp_nuc</span>"
                    }
                    my ($three_prime, $seq3);
                    $seq3 = join ('<BR>' ,  @{ $pcr_seq->{three_prime_flanking_region} }  ) if  $pcr_seq->{three_prime_flanking_region}  ;
                    if ($seq3) {
                      $three_prime = "3' flanking region";
                      $seq3 = "<span class=\"assay\">$seq3</span>"
                    }
                    my ($five_prime, $seq5);
                    $seq5 = join ('<BR>' ,  @{ $pcr_seq->{five_prime_flanking_region} }  ) if  $pcr_seq->{five_prime_flanking_region}  ;
                    if ($seq5) {
                      $five_prime = "5' flanking region";
                      $seq5 = "<span class=\"assay\">$seq5</span>"
                    }
                    my ($indel, $indel_seq);
                    $indel_seq = join ('<BR>' ,  @{ $pcr_seq->{indel} }  ) if  $pcr_seq->{indel}  ;
                    if ($indel_seq) {
                      $indel = "Indel";
                      $indel_seq = "<span class=\"indel\">$indel_seq</span>"
                    }
		    $locations_html .= '<br />';
                    $locations_html .=
                      CXGN::Page::FormattingHelpers::info_table_html(
                        '__title' =>
"PCR data&nbsp;&nbsp;&nbsp;<span class=\"tinytype\">Exp. ID "
                          . $pcr->pcr_experiment_id()
                          . "</span>",
                        "Forward primer (5'-3')" =>
                          "<span class=\"sequence\">$fwd</span>",
                        "Reverse primer (5'-3')" =>
                          "<span class=\"sequence\">$rev</span>",
                        $dcaps_left                     => $dcaps_right,
                       'Accessions and product sizes'  => $pcr_bands_html,
                        $digest_title                   => $digest_bands_html,
			'Enzymes'                       => $additional_enzymes,
                        'Approximate temperature'       => $temp,
                        'Mg<sup>+2</sup> concentration' => $mg,
                        '__multicol'                    => 3,
                        '__tableattrs'                  => "width=\"100%\"",
                      ) if ($protocol ne 'SNP');
                    my ($snpdb_format, $snpdb);
                    if ($snp_nuc) {
                      $snpdb = "SNPdb format";
                      my @fives = @{ $pcr_seq->{five_prime_flanking_region} } ;
                      my @threes = @{ $pcr_seq->{three_prime_flanking_region} } ;
                      my @snps  =  @{ $pcr_seq->{SNP} };
                      for my $i ( 0 .. (scalar( @snps ) -1 ) ) {
                        my $snp_string =  $snps[$i] ;
                        my $formatted = "[" . substr($snp_string, 0, 1) . "/" . substr($snp_string, -1) ."]";
                        my $five_p = $fives[$i];
                        my $three_p = $threes[$i];
                        $snpdb_format .= $five_p . $formatted ."<BR />" .  $three_p . "<BR />";
                      }
                    }
                    $locations_html .=
                      CXGN::Page::FormattingHelpers::info_table_html(
                        '__title' =>
"Assay data&nbsp;&nbsp;<span class=\"tinytype\"></span>",
                       $five_prime       => $seq5,
                       $three_prime       => $seq3,
                       $snpdb => $snpdb_format,
                       $aspe  => $aspe_primers,
                       $snp   => $snp_nuc,
                       $indel => $indel_seq,
                       '__multicol'    => 2,
                      '__tableattrs'   => "width=\"100%\"",
                      ) if $aspe || $indel || ($protocol eq "SNP");
                    $locations_html .= '</td></tr></table>';
                    push( @displayed_pcr, $pcr->pcr_experiment_id() )
                  }
            }
        }
    }
}

#line 322 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print( '
' );
#line 323 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->comp( { content => sub {
#line 323 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print( '
  ' );
#line 324 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print(  $locations_html  );
#line 324 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print( '
' );
#line 325 "/home/production/cxgn/sgn/mason/markers/locations.mas"
} }, '/page/info_section.mas', title=>'Mapped locations', collapsible=>1, collapsed=>0
 );
#line 325 "/home/production/cxgn/sgn/mason/markers/locations.mas"
$m->print( '
' );
;return;
},
'declared_args' => {
  '$marker' => { default => undef }
},
'load_time' => 1763079527,

)
;