#!/usr/bin/perl

our $VERSION = '0.02';

# $Id: polymorphic_between_accessions_step2,v 1.5.2.2 2007/06/14 19:04:09 kclark Exp $

use warnings;
use strict;

use FindBin::Real qw(Bin);
use HTML::SearchPage;
use HTML::SearchPage::Param;
use Panzea::FormModifier;
use Panzea::FormConfig;

my $config_file = '/usr/local/gramene-25/conf//html-searchpage.conf'; # MKFILE:Q:CONF_FILE

my $config = Panzea::FormConfig->new($config_file);

# Search page object
my $sp = HTML::SearchPage->new(
    page_title     => 'Polymorphism Between Two Accessions (Step Two)',
    header         => $config->cfg('form_header'),
    css            => $config->cfg('form_css'),
    temp_dir       => $config->cfg('temp_dir'),
    temp_dir_eq    => $config->cfg('temp_dir_eq'),
    instructions   => $config->cfg('instructions_poly_search'),
    footer         => $config->cfg('form_footer'),
    base_sql_table => qq[aux_genotype_by_accession agba_a
                         JOIN aux_genotype_by_accession agba_b ON (agba_b.cdv_marker_id = agba_a.cdv_marker_id)
                         ],
    base_sql_fields => [
        'agba_a.marker_name',
        'agba_a.feature_name',
        qq[CONCAT(agba_a.aux_map_info_id, ':', agba_a.ibm2_2005_chr)],
        'agba_a.ibm2_2005_position',
        'agba_a.marker_type',
        'agba_a.accename',
        'agba_a.div_obs_unit_id',
        'agba_a.formatted_genotype',
        'agba_b.accename',
        'agba_b.div_obs_unit_id',
        'agba_b.formatted_genotype',
        qq[IF((agba_a.resolved_genotype = agba_b.resolved_genotype) IS NULL,"Not Available",IF((agba_a.resolved_genotype = agba_b.resolved_genotype),"Match","Polymorphic"))],
        'agba_a.marker_name',
    ],
    base_output_headers => [
        'Marker:agba_a.marker_name',
        'Gene/Locus:agba_a.feature_name',
        'IBM2 Chr.:agba_a.sort_ibm2_2005_chr',
        'IBM2 Position:agba_a.sort_ibm2_2005_position',
        'Marker Type',
        'Accession1',
        'PlantId1:agba_a.div_obs_unit_id',
        'Genotype1',
        'Accession2',
        'PlantId2:agba_b.div_obs_unit_id',
        'Genotype2',
        'Comparison',
        'Annotation',
    ],
    sort_fields   => 3,
    sort_defaults => [
        'asc', 'agba_a.sort_ibm2_2005_chr', 'asc',
        'agba_a.sort_ibm2_2005_position'
    ],
    method           => $config->cfg('form_method'),
    page_size        => $config->cfg('form_page_size'),
    db_access_params => $config->cfg('db_access_params'),
    debug_level      => $config->cfg('form_debug_level'),
    go_to_results    => $config->cfg('form_go_to_results'),
    show_search_url  => $config->cfg('form_show_search_url'),
    modifier         => Panzea::FormModifier->new(),
    no_reset         => 1,
    new_search => "/db/searches/webform/polymorphic_between_accessions_step1",
); # Displays error page if fails

# Intermediary steps
my $marker_type = $sp->cgi_params->{'marker_type'};
my $accession1  = $sp->cgi_params->{'accession1'};

my $dbh = $sp->dbh;

# Make sure a marker type is available
if (!$marker_type or ($marker_type ne 'SNP' and $marker_type ne 'SSR')) {
    $sp->display_error_page("A valid marker type is required!");
}

# Make sure a marker type is available
if (!$accession1) {
    $sp->display_error_page("A valid accession1 is required!");
}

# Determine Accession 2 options
my @accession2s;

eval {

    # Check if aux_genotype_by_accession_count exists
    my $check_table;

    my $check_table_sth =
      $dbh->prepare(qq[SHOW TABLES LIKE 'aux_genotype_by_accession_count']);
    $check_table_sth->execute;
    ($check_table) = $check_table_sth->fetchrow_array;

    # Check if aux_genotype_by_accession_count contains any rows
    my $check_table_rows;

    if ($check_table) {
        my $check_table_rows_sth =
          $dbh->prepare(
            qq[SELECT COUNT(*) FROM aux_genotype_by_accession_count]);
        $check_table_rows_sth->execute;
        ($check_table_rows) = $check_table_rows_sth->fetchrow_array;
    }

    # Search count table if exists
    if ($check_table_rows) {
        my $query_sth = $dbh->prepare(
            qq[SELECT accename2, count_accename
               FROM
               aux_genotype_by_accession_count agbac
               WHERE
                   agbac.marker_type = ?
               AND agbac.accename1   = ?]
        );

        $query_sth->bind_param(1, $marker_type);
        $query_sth->bind_param(2, $accession1);

        $query_sth->execute;

        while (my ($accession2, $count_accession2) =
            $query_sth->fetchrow_array) {
            push @accession2s, $sp->url_encode($accession2) . ":"
              . $sp->url_encode("$accession2 ($count_accession2)");
        }
    }

    # Search main table if cannot find any rows up to this point
    if (!@accession2s) {
        my $query_sth = $dbh->prepare(
            qq[SELECT agba_b.accename AS accession2, COUNT(*) AS count_accession2
               FROM
                    aux_genotype_by_accession agba_a
               JOIN aux_genotype_by_accession agba_b ON (agba_b.cdv_marker_id = agba_a.cdv_marker_id)
               WHERE
                   agba_a.marker_type   = ?
               AND agba_a.accename  = ?
               AND agba_b.accename != ?
               GROUP BY agba_b.accename]
        );

        $query_sth->bind_param(1, $marker_type);
        $query_sth->bind_param(2, $accession1);
        $query_sth->bind_param(3, $accession1);

        $query_sth->execute;

        while (my ($accession2, $count_accession2) =
            $query_sth->fetchrow_array) {
            push @accession2s, $sp->url_encode($accession2) . ":"
              . $sp->url_encode("$accession2 ($count_accession2)");
        }
    }

};

$sp->display_error_page($@) if $@;

# Param fields
my $pf;

$pf = HTML::SearchPage::Param->new(
    -label            => 'Marker Type:',
    -sql_column       => 'agba_a.marker_type',
    -form_name        => 'marker_type',
    -operator_display => 0,
    -operator_default => '=',
    -param_type       => 'drop_down',
    -param_list       => [$sp->url_encode($marker_type)],
    -auto_all         => 0,
    -auto_null        => 0,
    -param_default    => [$sp->url_encode($marker_type)],
) or $sp->display_error_page($@);

$sp->param_field('marker_type', $pf);

$pf = HTML::SearchPage::Param->new(
    -label            => 'Accession 1:',
    -sql_column       => 'agba_a.accename',
    -form_name        => 'accession1',
    -operator_display => 0,
    -operator_default => '=',
    -param_type       => 'drop_down',
    -param_list       => [$sp->url_encode($accession1)],
    -auto_all         => 0,
    -auto_null        => 0,
    -param_default    => [$sp->url_encode($accession1)],
) or $sp->display_error_page($@);

$sp->param_field('accename1', $pf);

$pf = HTML::SearchPage::Param->new(
    -label            => 'Accession 2:',
    -sql_column       => 'agba_b.accename',
    -form_name        => 'accession2',
    -operator_display => 0,
    -operator_default => '=',
    -param_type       => 'drop_down',
    -param_list       => \@accession2s,
    -auto_all         => 0,
    -auto_null        => 0,
) or $sp->display_error_page($@);

$sp->param_field('accename2', $pf);

$pf = HTML::SearchPage::Param->new(
    -label => 'Comparison:',
    -sql_column =>
      qq[IF((agba_a.resolved_genotype = agba_b.resolved_genotype) IS NULL,"Not Available",IF((agba_a.resolved_genotype = agba_b.resolved_genotype),"Match","Polymorphic"))],
    -form_name        => 'comparison',
    -operator_display => 0,
    -operator_default => '=',
    -param_type       => 'drop_down',
    -param_list       => ['Match', 'Polymorphic', 'Not Available'],
    -auto_all         => 1,
    -auto_null        => 0,
) or $sp->display_error_page($@);

$sp->param_field('comparison', $pf);

$pf = HTML::SearchPage::Param->new(
    -label            => 'IBM2 Chromosome:',
    -sql_column       => 'agba_a.ibm2_2005_chr',
    -form_name        => 'ibm2_2005_chr',
    -operator_list    => ['=:equals'],
    -operator_display => 0,
    -operator_default => '=',
    -param_type       => 'drop_down',
    -param_list       => [
        qq[DISTINCT:SELECT distinct ibm2_2005_chr FROM aux_map_info
           WHERE ibm2_2005_chr IS NOT NULL ORDER BY ibm2_2005_chr]
    ],
    -auto_all      => 1,
    -auto_null     => 1,
    -param_default => ['all'],
) or $sp->display_error_page($@);
$sp->param_field('chromosome', $pf);

$pf = HTML::SearchPage::Param->new(
    -label            => 'Position (from cM):',
    -sql_column       => 'agba_a.ibm2_2005_position',
    -form_name        => 'position_from',
    -operator_list    => ['>=:from'],
    -operator_display => 0,
    -param_type       => 'text:12',
) or $sp->display_error_page($@);

$sp->param_field('position_from', $pf);

$pf = HTML::SearchPage::Param->new(
    -label            => 'Position (to cM):',
    -sql_column       => 'agba_a.ibm2_2005_position',
    -form_name        => 'position_to',
    -operator_list    => ['<=:to'],
    -operator_display => 0,
    -param_type       => 'text:12',
) or $sp->display_error_page($@);

$sp->param_field('position_to', $pf);

# Modifications
$sp->add_modification(
    -action => 'add_link',
    -column => 1,
    -type   => 'gene_locus'
);

$sp->add_modification(
    -action => 'add_link',
    -type   => 'maizegdb_ibm2n',
    -column => 2,
);

$sp->add_modification(
    -action => 'add_link',
    -column => 6,
    -type   => 'accession'
);

$sp->add_modification(
    -action => 'add_link',
    -column => 9,
    -type   => 'accession'
);

$sp->add_modification(
    -action  => 'get_marker_annotations',
    -column  => 12,
    -profile => 'moldiversity_search',
);

# Call display method
$sp->display_page;

=head1 NAME

polymorphic_between_accessions_step2

=head1 DESCRIPTION

Panzea web display script.

Please refer to documentation of HTML::SearchPage and
HTML::SearchPage::Param for information on script structure.

=head1 AUTHOR

Payan Canaran <canaran@cshl.edu>

=head1 BUGS

=head1 VERSION

Version 0.02

=head1 ACKNOWLEDGEMENTS

=head1 COPYRIGHT & LICENSE

Copyright (c) 2005-2007 Cold Spring Harbor Laboratory

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself. See DISCLAIMER.txt for
disclaimers of warranty.

=cut

