#!/opt/conda/conda-bld/trinotate_1694220261901/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pla/bin/perl 

use strict;
use warnings;

use FindBin;

use CanvasXpress::Sunburst;
use CanvasXpress::Piechart;
use CanvasXpress::Barplot;

use CanvasXpress::PlotOnLoader;

use CGI;

my $usage = "usage: $0 report_prefix\n\n";

my $report_prefix = $ARGV[0] or die $usage;


my $plot_loader = new CanvasXpress::PlotOnLoader("load_plots");

main: {

    my $cgi = new CGI();

    
    print $cgi->start_html(-title => "Trinotate Report: $report_prefix",
                           -onLoad => "load_plots();");
    print" <style>  body{font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;font-size: 14px;line-height: 1.42857143;color: #333;background-color: #fff;} .side-nav {height: 100%;width: 250px;border-right: 1px solid #ccc;position: fixed;z-index: 1;top: 0;left: 0;overflow-x: hidden;transition:.4s;padding-top: 20px;background-color: #222224;}.side-bar{height: 100%;width: 250px;border-right: 1px solid #ccc;z-index: 1;top: 0;left:-250px;overflow-x: hidden;padding-top: 20px;background-color: #222224;}.side-bar button{ left:0px;}.side-nav a {padding: 6px 8px 6px 16px;text-decoration: none;font-size: 19px;color: #ccc;display: block;}.side-nav a:hover {background-color: #dedede;text-decoration: none;color:#0f0d0d;}.glyphicon {position: relative;top: 1px;display: inline-block;font-family: 'Glyphicons Halflings';font-style: normal;font-weight: 400;line-height: 1;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale}.main {margin-left: 160px; /* Same as the width of the sidenav */font-size: 28px; /* Increased text to enable scrolling */padding: 0px 10px;}/@/media screen and (max-height: 450px) {.sidenav {padding-top: 15px;}.sidenav a {font-size: 18px;}}.side-nav ul {margin: 0;padding: 0;list-style-type: none;border-bottom: 1px solid rgb(63, 62, 62);}.side-nav a.nav-l1 {padding: 20px;border-top: 1px solid rgb(63, 62, 62);}.side-bar-btn{    background-color: grey!important;    margin:5px;    position:fixed;}.side-nav h1 {font-size: 18px;text-align: center;margin: 0;margin-top:40px;/* border-bottom: 1px solid #ccc; */}  </style>\n"; 
    print" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/canvasXpress/29.0/canvasXpress.css\" type=\"text/css\"/>\n";
    print" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/canvasXpress/29.0/canvasXpress.min.css\" type=\"text/css\">\n";
    print" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" type=\"text/css\"/>\n";
    print" <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script>\n";
    print" <script src=\"https://cdn.jsdelivr.net/npm/popper.js.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script>\n";
    print" <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"></script>\n";
    print" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" type=\"text/css\"/>\n\n\n";
        
    print"<div class=\"side-nav-wrapper\">\n";
            print"<div class=\"side-nav \">\n";
            print"<div class=\"custom-menu\">\n";
                print"<button type=\"button\" id=\"sidebarCollapse\" class=\"btn side-bar-btn\">\n";
                print"<i class=\"fa fa-bars\"></i>\n";
                print"<span class=\"sr-only\">Toggle Menu</span>\n";
                print"</button>\n";
            print"</div>\n";
            print"<h1><a href=\"#\"><img width=\"120px\" height=\"70px\" src=\"data:image/png;base64,[encoded data, 310264 characters]\" alt=\"Logo\"></a></h1>\n";
            print"<ul>\n";
                print"<li class=\"active\"><a class=\"nav-l1\" href=\"#mydiv\"><span class=\"fa fa-sticky-note\"></span>  Taxonomy </a></li>\n" ;
                print"<li><a class=\"nav-l1\" href=\"#mydiv1\"><span class=\"fa fa-sticky-note\"></span>  Top species </a></li>\n" ;
                print"<li><a class=\"nav-l1\" href=\"#mydiv2\"><span class=\"fa fa-sticky-note\"></span>  Gene Ontology </a></li>\n" ;
                print"<li><a class=\"nav-l1\" href=\"#mydiv3\"><span class=\"fa fa-sticky-note\"></span>  Top Pfam </a></li>\n ";
                print"<li><a class=\"nav-l1\" href=\"#mydiv4\"><span class=\"fa fa-sticky-note\"></span>  Functional Category </a></li>\n ";
                print"<li><a class=\"nav-l1\" href=\"#mydiv5\"><span class=\"fa fa-sticky-note\"></span>  Top KEGG </a></li>\n"; 
            print"</ul>\n";
        print"</div>\n";
    print"</div>\n\n\n";

   
    print"<div class=\"main \">\n"; 
    print"   <hr><div class=\"title\"><center><h2> Trinotate:Transcriptome Functional Annotation and Analysis </h2></center></div><hr>\n";
      
    print"    <div id=\"mydiv\"><h4>Taxonomy</h4><p style=\"font-size:15px\">Taxonomic representation of top swissprot matches</p>\n";
    print"      <hr class=\"w3-clear\"><br>";
    print"      <canvas id=\"taxonomy_sunburst\" width=\"800\" height=\"500\"></canvas></div>\n";
    print"    <hr><div id=\"mydiv1\"><h4>Top species</h4><p style=\"font-size:15px\">Most abundant species represneted by top swissprot blast matches</p>\n";
    print"      <hr class=\"w3-clear\"><br> <canvas id=\"top_species_piechart\" width=\"800\" height=\"500\"></canvas></div>\n";
    print"    <hr><div id=\"mydiv2\"><h4>Gene Ontology</h4><p style=\"font-size:15px\">Gene ontology slim category assignments based on swissprot blast matches</p>\n";
    print"      <hr class=\"w3-clear\"><br> <canvas id=\"GO_sunburst\" width=\"800\" height=\"500\"></canvas></div>\n";
    print"    <hr><div id=\"mydiv3\"><h4>Top Pfam</h4><p style=\"font-size:15px\">Most abundant pfam domains based on protein searches</p>\n";
    print"      <hr class=\"w3-clear\"><br> <canvas id=\"Pfam_barplot\" width=\"800\" height=\"500\"></canvas></div>\n";
    print"    <hr><div id=\"mydiv4\"> <h4>Functional Category</h4><p style=\"font-size:15px\">Most abundant Eggnog functional categories based on top swissprot matches</p>\n";
    print"      <hr class=\"w3-clear\"><br><canvas id=\"funccat_barplot\" width=\"800\" height=\"500\"></canvas></div>\n";
    print"    <hr><div id=\"mydiv5\"><h4>Top KEGG</h4><p style=\"font-size:15px\">Most abundant KEGG assignments based on top swissprot matches</p>\n";
    print"      <hr class=\"w3-clear\"><br> <canvas id=\"kegg_barplot\" width=\"800\" height=\"500\"></canvas></div>\n";

    print"</div>\n\n";
    print"<script>\n";
    print"  \$\(document).ready(function(){\n";
      
     print" \$\(\'canvas\').each(function(){\n";
    print"  if(\$\(this).siblings().length > 1){\n";
    print"   }else{\n";
    print"  \$\(this).parent().hide();\n";
    print" }\n";
    print" })\n";
      
    print"    \$\(\".side-bar-btn\").click(function(){\n";
    print"       \$\(\".side-nav\").toggleClass(\"side-bar\");\n";   
    print"    });\n";
    print"  });\n";
   
    print"</script>\n";
    
    ## taxonomy report
    &generate_taxonomy_report_html("$report_prefix.taxonomy_counts");

    ## top species report
    &generate_top_species_report_html("$report_prefix.species_counts");


    ## Gene Ontology view
    &generate_gene_ontology_view("$report_prefix.GO.slim");

    ## Pfam domains:
    &generate_pfam_domain_barplot("$report_prefix.pfam.counts");

    ## Eggnog funccats:
    &generate_eggnog_funccat_barplot("$report_prefix.eggnog_counts.funcats");
    
    ## KEGG
    &generate_KEGG_view("$report_prefix.kegg.counts");


    print $plot_loader->write_plot_loader();
    
    print $cgi->end_html();

    exit(0);
}


####
sub generate_taxonomy_report_html {
    my ($data_file) = @_;

    my $NUM_TOP_CATS = 50;

    open(my $fh, $data_file) or die "Error, cannot open file: $data_file";
    my $header = <$fh>;
    chomp $header;
    my @levels = split(/\t/, $header);
    pop @levels; # count value

    my @row_values;
    my @column_data;
    my $other_counts = 0;
    my $counter = 0;
    while (<$fh>) {
        $counter++;
        chomp;
        my @x = split(/\t/);
        my $count = pop @x;

        if ($counter < $NUM_TOP_CATS) {
            for(my $i = 0; $i <= $#x; $i++) {
                push (@{$column_data[$i]}, $x[$i]);
            }
            push (@row_values, $count);
        }
        else {
            $other_counts += $count;
        }
    }
    close $fh;

    if ($other_counts) {
        # build other counts entry:
        my @columns = @column_data;
        my $first_col = shift @columns;
        push (@$first_col, "Other");
        foreach my $other_col (@columns) {
            push (@$other_col, "NA");
        }
        push (@row_values, $other_counts);
    }


    # convert column data to hash:
    my %column_data_hash;
    for (my $i = 0; $i <= $#levels; $i++) {

        my $level = $levels[$i];
        my $col_data_aref = $column_data[$i];
        $column_data_hash{$level} = $col_data_aref;
    }

    my $taxonomy_sunburst = new CanvasXpress::Sunburst("taxonomy_sunburst");
    $plot_loader->add_plot($taxonomy_sunburst);

    my %inputs = (title =>  "Taxonomic representation of gene-level top blastx matches",

                  column_names => [@levels],

                  column_contents => \%column_data_hash,

                  row_values => [@row_values]);

   
        print $taxonomy_sunburst->draw(%inputs);


}



####
sub generate_top_species_report_html{
    my ($data_file) = @_;

    my $MIN_PCT = 2;

    my @vals;
    open(my $fh, $data_file) or die "Error, cannot open file: $data_file";
    my $header = <$fh>;
    my $total_count = 0;
    while (<$fh>) {
        chomp;
        my ($species, $count) = split(/\t/);
        push (@vals, [$species, $count]);
        $total_count += $count;
    }
    close $fh;

    my @pie_slices;
    my $other_counts = 0;
    foreach my $val_pair (@vals) {
        my ($species, $count) = @$val_pair;
        my $pct = $count / $total_count * 100;
        if ($pct >= $MIN_PCT) {
            push (@pie_slices, $val_pair);
        }
        else {
            $other_counts += $count;
        }
    }

    if ($other_counts) {
        push (@pie_slices, ["other", $other_counts]);
    }

    my $piechart = new CanvasXpress::Piechart("top_species_piechart");

    $plot_loader->add_plot($piechart);

    my %inputs = (pie_name => "Top species represented",
                  pie_slices => [@pie_slices]);

    print $piechart->draw(%inputs);
  
}


####
sub generate_gene_ontology_view {
    my ($data_file) = @_;


    my @column_names = ("go_class", "go_term");
    my %column_data;
    my @row_values;

    open(my $fh, $data_file) or die "Error, cannot open file $data_file";
    while (<$fh>) {
        chomp;
        unless (/\w/) { next; }
        my @x = split(/\t/);
        my ($go_class, $go_id, $go_term, $count, $go_descr) = @x;


        if ($go_term =~ /^(biological_process|cellular_component|molecular_function)$/) { next; } # skip highest-level


        $go_id =~ s/:/_/g;

        $go_term = "$go_id $go_term";

        push (@{$column_data{'go_class'}}, $go_class);
        push (@{$column_data{'go_term'}}, $go_term);
        push (@row_values, $count);
    }
    close $fh;

    my $GO_sunburst = new CanvasXpress::Sunburst("GO_sunburst");
    $plot_loader->add_plot($GO_sunburst);

    my %inputs = (title => "Gene Ontology Categories",

                  column_names => [@column_names],

                  column_contents => \%column_data,

                  row_values => [@row_values] );

    print $GO_sunburst->draw(%inputs);


    return;
}

####
sub generate_pfam_domain_barplot {
    my ($data_file) = @_;

    my $NUM_TOP_DOMAINS = 50;

    open(my $fh, $data_file) or die "Error, cannot open file: $data_file";
    my $header = <$fh>;

    my @vals;
    my $counter = 0;
    while (<$fh>) {
        chomp;
        $counter++;

        my ($pfam, $count) = split(/\t/);

        push (@vals, [$pfam, $count]);

        if ($counter >= $NUM_TOP_DOMAINS) { last; }

    }
    close $fh;


    my %inputs = ( orientation => 'horizontal',

                   title => 'Top Pfam domains',

                   var_name => 'Pfam',

                   data => [@vals],
        );

    my $barplot = new CanvasXpress::Barplot("Pfam_barplot");
    $plot_loader->add_plot($barplot);

    print $barplot->draw(%inputs);

    return;
}


####
sub generate_eggnog_funccat_barplot {
    my ($data_file) = @_;

    my @vals;
    open(my $fh, $data_file) or die "Error, cannot open file: $data_file";
    my $header = <$fh>;
    while (<$fh>) {
        chomp;
        my ($code, $funccat, $count) = split("\t");

        if ($code eq "S" || $code eq "R") { next; } # nonspecific categories

        push (@vals, [$funccat, $count]);
    }
    close $fh;


    my %inputs = ( orientation => 'horizontal',

                   title => 'Functional Categories via Eggnog/COG Mappings',

                   var_name => 'funccats',

                   data => [@vals],
        );

    my $barplot = new CanvasXpress::Barplot("funccat_barplot");
    $plot_loader->add_plot($barplot);

    print $barplot->draw(%inputs);

    return;

}
sub generate_KEGG_view {
    my ($data_file) = @_;

    my $NUM_TOP_DOMAINS = 50;

    open(my $fh, $data_file) or die "Error, cannot open file: $data_file";
    my $header = <$fh>;

    my @vals;
    my $counter = 0;
    while (<$fh>) {
        chomp;
        $counter++;

        my ($kegg, $count) = split(/\t/);

        push (@vals, [$kegg, $count]);

        if ($counter >= $NUM_TOP_DOMAINS) { last; }

    }
    close $fh;


    my %inputs = ( orientation => 'horizontal',

                   title => 'Top KEGG domains',

                   var_name => 'kegg',

                   data => [@vals],
        );

    my $barplot = new CanvasXpress::Barplot("kegg_barplot");
    $plot_loader->add_plot($barplot);

    print $barplot->draw(%inputs);

    return;
}


