#!/usr/bin/perl

our $VERSION = '0.02';

# $Id: genotypes_in_map,v 1.2.2.2 2007/06/14 19:04:09 kclark Exp $

use warnings;
use strict;

use CGI;
use FindBin::Real qw(Bin);
use Panzea::FormConfig;
use Panzea::GMapView;
use Panzea::WebFormUtils;

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

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

my $code2sampstat = Panzea::WebFormUtils->code2sampstat();

# Gmap object
my $gv = Panzea::GMapView->new(
    page_title      => "Geographic Display",
    header          => $config->cfg('form_header'),
    footer          => $config->cfg('form_footer'),
    base_sql_table  => qq[aux_assay_plant_genotype aapg],
    base_sql_fields => [
        'aux_assay_plant_genotype_id',
        'latitude',
        'longitude',
        'marker_name',
        'marker_type',
        'germplasm_type',
        'allele_value',
    ],
    detail_fields => [
        'marker_name',
        'marker_type',
        'germplasm_type',
        'allele_value',
    ],
    base_output_headers => [
        'Id',
        'Latitude',
        'Longitude',
        'Marker Name',
        'Marker Type',
        'Germplasm Type',
        'Allele Value',
    ],
    db_access_params => $config->cfg('db_access_params'),
    gmap_key         => $config->cfg('gmap_key'),
    temp_dir         => $config->cfg('temp_dir'),
    temp_dir_eq      => $config->cfg('temp_dir_eq'),
    initial_format   => 'xml-piechart',
    cluster_field    => 'allele_value',
    image_height_pix => 540,
    image_width_pix  => 540,
    tile_height_pix  => 60,
    tile_width_pix   => 60,
);    # Displays error page if fails

# Prepare for determining script params
my $cgi = $gv->cgi;
my $dbh = $gv->dbh;

# Determine marker_name
my $marker_name = $cgi->param("marker_name")
  or $gv->error("A marker_name is required!");

# Determine marker_type
my $marker_type = $cgi->param("marker_type")
  or $gv->error("A marker_type is required!");

# Determine germplasm_types
my @germplasm_types;

#my @germplasm_types_w_counts;
eval {
    my $statement =
      qq[SELECT aapg.germplasm_type, count(aapg.germplasm_type) as germplasm_type_count
         FROM  aux_assay_plant_genotype aapg
         WHERE aapg.germplasm_type IS NOT NULL
         AND   aapg.germplasm_type != ""
         AND   aapg.allele_value IS NOT NULL
         AND   aapg.allele_value != ""
         AND   aapg.latitude IS NOT NULL
         AND   aapg.longitude IS NOT NULL
         AND   aapg.marker_name = ?
         AND   aapg.marker_type = ?
         GROUP BY aapg.germplasm_type
         ORDER BY germplasm_type_count DESC
         ];

    my $sth = $dbh->prepare($statement);

    $sth->bind_param(1, $marker_name);
    $sth->bind_param(2, $marker_type);

    $sth->execute;

    while (my ($germplasm_type, $count) = $sth->fetchrow_array) {
        push @germplasm_types, $germplasm_type;
    }
};
$gv->error($@) if $@;

# Determine allele_values
my @allele_values;

#my @allele_values_w_counts;
eval {
    my $statement =
      qq[SELECT aapg.allele_value, count(aapg.allele_value) as allele_value_count
         FROM  aux_assay_plant_genotype aapg
         WHERE aapg.germplasm_type IS NOT NULL
         AND   aapg.germplasm_type != ""
         AND   aapg.allele_value IS NOT NULL
         AND   aapg.allele_value != ""
         AND   aapg.latitude IS NOT NULL
         AND   aapg.longitude IS NOT NULL
         AND   aapg.marker_name = ?
         AND   aapg.marker_type = ?
         GROUP BY aapg.allele_value
         ORDER BY allele_value_count DESC
         ];

    my $sth = $dbh->prepare($statement);

    $sth->bind_param(1, $marker_name);
    $sth->bind_param(2, $marker_type);

    $sth->execute;

    while (my ($allele_value, $count) = $sth->fetchrow_array) {
        push @allele_values, $allele_value;
    }
};
$gv->error($@) if $@;

# Determine center coordinates
my $center_latitude;
my $center_longitude;
eval {
    my $statement =
      qq[SELECT avg(latitude), avg(longitude)
         FROM  aux_assay_plant_genotype aapg
         WHERE aapg.germplasm_type IS NOT NULL
         AND   aapg.germplasm_type != ""
         AND   aapg.allele_value IS NOT NULL
         AND   aapg.allele_value != ""
         AND   aapg.latitude IS NOT NULL
         AND   aapg.longitude IS NOT NULL
         AND   aapg.marker_name = ?
         AND   aapg.marker_type = ?
         ];

    my $sth = $dbh->prepare($statement);

    $sth->bind_param(1, $marker_name);
    $sth->bind_param(2, $marker_type);

    $sth->execute;

    ($center_latitude, $center_longitude) = $sth->fetchrow_array;
};
$gv->error($@) if $@;

$gv->center_latitude($center_latitude);
$gv->center_longitude($center_longitude);

# Determine invalid data points and report as message
my $count_valid;
my $count_invalid;
my $count_all;
eval {
    my $statement =
      qq[SELECT count_valid, count_invalid, count_all
         FROM  aux_assay_plant_genotype_count aapgc
         WHERE aapgc.marker_name = ?
         AND   aapgc.marker_type = ?
         ];

    my $sth = $dbh->prepare($statement);

    $sth->bind_param(1, $marker_name);
    $sth->bind_param(2, $marker_type);

    $sth->execute;

    ($count_valid, $count_invalid, $count_all) = $sth->fetchrow_array;
};
$gv->error($@) if $@;

if (!$count_all) {
    $gv->messages("- This dataset does not contain any data points.");
}
elsif (!$count_valid) {
    $gv->messages(
        "- This dataset contains $count_all valid (non-N and non-nd) data point(s), none of which are displayed (due to invalid geographical coordinates)."
    );
}
elsif (!$count_invalid) {
    $gv->messages(
        "- This dataset contains $count_all valid (non-N and non-nd) data point(s), all of which are displayed."
    );
}
else {
    $gv->messages(
        "- This dataset contains $count_all valid (non-N and non-nd) data point(s), of which $count_invalid are not displayed due to invalid geographical coordinates."
    );
}

# Set param_fields for the gv object
my @formatted_allele_values   = map { _format_label($_); } @allele_values;
my @formatted_germplasm_types = map { _format_label($_); } @germplasm_types;
$gv->param_fields(
    {   "marker_name"    => [$marker_name],
        "marker_type"    => [$marker_type],
        "germplasm_type" => ["all:ALL", @formatted_germplasm_types],
        "allele_value"   => ["all:ALL", @formatted_allele_values],
    }
);

# Call display method
$gv->display;

sub _format_label {
    my ($label) = @_;

    my $formatted_label = $label;

    if ($formatted_label =~ s/^(.{12}).+/$1/) {
        $formatted_label .= " ...";
    }

    return "$label:$formatted_label";
}

=head1 NAME

genotypes_in_map

=head1 DESCRIPTION

Panzea web display script.

Please refer to documentation of HTML::GMap 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

