<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bohra {{job_id}}</title>
 
    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!-- Optional theme -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap-theme.min.css" rel="stylesheet">
    

    <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.dataTables.min.css" rel="stylesheet">

    <!-- LOCAL STYLE -->
    <!-- <link href="job.css" rel="stylesheet"> -->

    <!-- Graphing library -->
    
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    
  
    <!-- Icon -->
    <script src="https://unpkg.com/feather-icons"></script>
    <!-- Datatables -->
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet">
    <link href="https//cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel = "stylesheet">
    <!-- drag select jquery -->
    <script src="https://thibaultjanbeyer.github.io/DragSelect/ds.min.js"></script>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <style type="text/css">
        h2, h3 {
          padding:10px;
        }
        header {
                background-color: #3973ac;
                color: aliceblue;
        }
        svg.text.branch-support {
          display:none;
          color:#3973ac;
          font-size: x-small;
        }
        .activeisolate {
          fill:#3973ac;
          font-size: larger;

        }
        @media (min-width: 768px) {
        .modal-xl {
        max-width: 90%; 
                }
        }

        .details {
                display: none;
        }
        .btn-outline-primary {
          color: #3973ac;
          border-color: #3973ac;
        }

        .btn-outline-primary:hover {
          background-color:  #3973ac;
          color: aliceblue;
        }

        .btn-outline-primary:not(:disabled):not(.disabled).active {
          background-color:  #3973ac;
          color: aliceblue;
        }

        #current-table {
          margin-top:20px;
        }

        .btn-outline-secondary {
          color: #3973ac;
          border-color: #3973ac;
        }

        .btn-outline-secondary:hover {
          background-color:  #3973ac;
          color: aliceblue;
        }

        .btn-outline-secondary:not(:disabled):not(.disabled).active {
          background-color:  #3973ac;
          color: aliceblue;
        }
        .page-link {
          color:#3973ac;
          
        }
        .page-item.active .page-link{
          background-color:  #3973ac;
          border-color:#3973ac;
          color: aliceblue;
        }

        
      </style> 
  </head>
  <body>
    <header>
      <h1 class="left">{{job_id}}</h1>
        <p class ="right"> Generated using Bohra microbial genomics pipeline {{date}} </p>
        <hr>
    </header>
  <!-- Modals - individual isolates -->
    <!-- Modal for tables for each isolate -->
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog modal-dialog-centered modal-xl" >
      <!-- Modal content-->
        <div class="modal-content">
            <h2 class="modal-title"> <!-- placeholder for isolate id --></h2>
            <h3 style= "color: #3973ac;">Summary Table</h3>
              <table id="" class="table table-striped table-bordered  modal-summary-table">
                  <thead>
                    <tr><!-- header of table -->
                          <th>Isolate</th>
                          <th>% Used</th>
                          <th>Coverage</th>
                          <th># Contigs</th>
                          <th>MLST</th>
                          <th>Species</th>
                    </tr>
                  </thead>
                  <tbody class='modal-body-summary-table'>

                  </tbody>
              </table>
            {% for t in td %}
            {% if t.type == 'table' %}
            <h3 style= "color: #3973ac;">{{ t.title }}</h3>
                <table id="" class="table table-striped table-bordered  modal-{{t.link}}">
                  <thead>{{ t.head }}</thead>
                  <tbody class='modal-body-{{t.link}}'>
                    
                  </tbody>
                </table>
            {% endif %}
            {% endfor %}          
          </div>
        </div>
      </div>
      <!-- modal for snp-distances -->
      <div class="modal fade" id="myModal2" role="dialog">
        <div class="modal-dialog modal-dialog-centered modal-xl" >
          <div class="modal-content">
            <h3 style= "color: #3973ac;"> SNP distances </h3>
              <table id="" class="table table-striped table-bordered  modal-selected-snps-table">
                          
              </table>
          </div>
        </div>
      </div>
  <!-- modal for help -->
    <div class="modal fade" id="myModal3" role="dialog">
      <div class="modal-dialog modal-dialog-centered modal" >
        <div class="modal-content">
          <h2 class="modal-title" style= "color: #3973ac; margin:3px;"> Information </h2>
          <hr>
          <<h3 style="margin:6px;"> Download tree</h3>
          <p style="margin:10px;"> To download a newick file right click on tree and select export as newick</p>
          <h3 style="margin:6px;"> Isolate details</h3>
          <p style="margin:10px;"> Select an isolate node from the tree to see isolate specific details</p>
          <h3 style="margin:6px;"> SNP distances </h3>
          <p style="margin:10px;"> Select the parent node to display pariwise SNP distances</p>
        </div>
      </div>
    </div>

<div id="help-button" style = "float:right;">
  <button type="button" class="btn btn-sm btn-outline-secondary zoom-button" id = "help" data-toggle="modal" data-target="#myModal3" data-placement="top" title="Select"> Helpful tips </button>    
  <button type="button" class="btn btn-sm btn-outline-secondary" id = "nwk" ><span data-feather="arrow-down"> Download newick </button>        
</div>
<!-- div for summary table and phylogenetic tree -->
<div class= "container-fluid">
    
    
      <!-- <h2 style = "color: #3973ac">Phylogeny and summary of isolates</h2> -->
      {% for t in td %}
      {% if t.type == 'summary' %}
      <!-- <h2 style= "color: #3973ac; float:left;" class='summary-table-header'>Summary Table</h2> -->
      <button type="button" class="btn btn-primary btn-xlg btn-outline-primary btn-lg summary-table-button" >{{t.title}}</button>
      {% elif t.type == 'tree' %}
      <!-- <h2 style= "color: #3973ac; float:right;" class='phylogeny-table-header'>Phylogeny</h2> -->
      <button type="button" class="btn btn-primary btn-xlg btn-outline-primary btn-lg phylogeny-button" >{{t.title}}</button>
      
      {% endif %}
      {% endfor %}
      
          
          <hr>
        {% for t in td %}
        
        {% if t.type == 'summary' %}
        <div id="tablediv" style = "display:none;"  >
          <table id="summary-table" class="table table-striped table-bordered table-sortable summary-table" style="width: 100%;">
              
              <thead>
                <tr>{{t.head}}</tr>
              </thead>
              <tbody>{{t.body}}</tbody>
                  <!-- end of table body -->
          </table>
        </div>
      </div>
      {% elif t.type == 'tree' %}
      <div id = "treediv" >
      <div id="tree_string" style="display: none;">{{newick}}</div>
      <div id="phylocanvas" style="width: 100%; height: {{tree_height}}; " >
      
        <!-- <p>{{message}}</p> -->
        
        <hr>
        <!-- button div -->
        <div class = "radial-div">
          <button id="change-tree" type="button" class="btn btn-sm btn-outline-secondary">Circular</button>
      </div>
        
        {% endif %}
        {% endfor %}
      
      
      
    </div>
  </div>
  </div>
  <!-- full width for detail tables and graphs-->
  <div class="container-fluid">
    <!-- button row -->
    <h2 id="detail-tables" style= "color: #3973ac;">Details</h2>
    <!-- buttons to select data for display -->
    <div id="detail-selection-buttons">
    {% for t in td %}
    {% if t.type == 'table' %}
      <button type="button" class="btn btn-primary btn-lg btn-outline-primary detail-button" >{{t.title}}</button>
    {% elif t.type == 'matrix' %}
      <button type="button" class="btn btn-primary btn-lg btn-outline-primary detail-button" >{{t.title}}</button>
    {% elif t.type == 'pan' %}
    <button type="button" class="btn btn-primary btn-lg btn-outline-primary detail-button" >{{t.title}}</button>
    
    {% endif %}
    {% endfor %}
    </div>

    <div id = "snp-distances-graph" class = "hidden-graph">  <!-- placeholder for graphs  --> </div>
    <div id = "snp-density-graph" class = "hidden-graph">  <!-- placeholder for graphs  --> </div>

    <div id="current-table">
            <!-- placeholder for selected table = put selected table in this div -->    
    </div>
    <br>

    {% for t in td %}
    {% if t.type == 'table' %}
    <!-- these tables are hidden until needed - then placed in the current table div above -->
    <div class="table-responsive">
      <!-- buttons for dowload -->
      <div id = "{{t.link}}" style = "display: none;">
        <h3>{{t.title}}</h3>  
        <table class="table table-striped table-bordered table-sortable detail-table">
          <thead>
            <tr><!-- header of table -->
              {{t.head}}
            </tr>
          </thead>
          <tbody>
            {{t.body}}
          </tbody>
                    <!-- end of table body -->
        </table>
      <!-- end of table -->
      </div>
    </div>
    {% elif t.type == 'matrix' %}
    <!-- these tables are hidden until needed - then placed in the current table div above -->
    <div class="table-responsive" >
      <!-- buttons for dowload -->
      <div id = "{{t.link}}" style="display:none;">
        <h3>{{t.title}}</h3>  
        <table class="table table-striped table-bordered table-sortable detail-table">
          <thead>
            <tr><!-- header of table -->
              {{t.head}}
            </tr>
          </thead>
          <tbody>
            {{t.body}}
          </tbody>
                    <!-- end of table body -->
        </table>
      <!-- end of table -->
      </div>
    </div>
    {% elif t.type == 'pan' %}
    <!-- these tables are hidden until needed - then placed in the current table div above -->
    <div class="table-responsive" >
      <!-- buttons for dowload -->
      <div id = "{{t.link}}" style = "display:none;">
        <h3>{{t.title}}</h3>  
        <table class="table table-striped table-bordered table-sortable detail-table">
          <thead>
            <tr><!-- header of table -->
              {{t.head}}
            </tr>
          </thead>
          <tbody>
            {{t.body}}
          </tbody>
                    <!-- end of table body -->
        </table>
      <!-- end of table -->
      {{t.image}}  
      </div>
    </div>
    

    
  
</div>
    {% endif %}
    {% endfor %}
  </div>
        
<!-- Datatables (to sort tables) -->
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<!-- <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script> -->
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script type="application/javascript" src="https://cdn.rawgit.com/phylocanvas/phylocanvas-quickstart/v2.8.1/phylocanvas-quickstart.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script src= "https://cdn.datatables.net/buttons/1.5.6/js/buttons.flash.min.js"></script>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>



{% block script %}
<script>
$(document).ready( function () {
// 

$("button.summary-table-button").click(function(){
  console.log('selected table');
  $("#tablediv").show();
  $("#treediv").hide();
});

$("button.phylogeny-button").click(function(){
  console.log('selected phylogeny');
  $("#tablediv").hide();
  $("#treediv").show();
});

// using phylocanvas to make tree
var nwk = $("#tree_string").text();
var tree = Phylocanvas.createTree('phylocanvas', {
  showInternalNodeLabels: true,
  alignLabels: true,
  lineWidth: 2,
  disableZoom: true,    
  scalebar: { active: true, position: { bottom: 10, centre: 10 } },
});  
tree.internalLabelStyle.colour = '#adf0ad';
tree.on('error', function (event) { throw event.error; });
tree.on('loaded', function () { console.log('loaded phylocanvas'); });
tree.load(nwk);
tree.setTreeType('rectangular');
tree.setTextSize(20);
tree.setNodeSize(4);
tree.draw();

// display modal tables from tree

tree.on('click', function (e) {
  var node = tree.getNodeAtMousePosition(e);
  console.log(node.getChildProperties('id'));
  var selected = node.getChildProperties('id');
  // snp-distances
  if (selected.length > 1) {
      var table_head = "<thead>\n<tr>\n<th></th>";
      var table_body = "<tbody>";
      for (var i = 0; i < selected.length; i++) {
          console.log(selected[i]);
          table_head = table_head + '<th>' + selected[i] + '</th>\n';
          var row = '<tr>\n';
          var first_cell= $('.' + selected[i] + '_snp-dists')[0].innerHTML;
          row = row + '<td>' + first_cell + '</td>';
          for (var j = 0; j < selected.length; j++) {
              console.log(selected[j]);
              console.log($('.'+selected[i]+'_'+selected[j])[0].innerHTML);
              var cell = $('.'+selected[i]+'_'+selected[j])[0].innerHTML;
              row = row +'<td>'+ cell + '</td>\n';
          }
          row = row + '</tr>\n';
          table_body = table_body + row;
      }
      table_head = table_head + '</tr>\n</thead>';
      table_body = table_body + '</tbody>';
      console.log(table_head);
      console.log(table_body);
      var t = table_head +table_body;
      $('.modal-selected-snps-table').html(t);
      $("#myModal2").modal();
  } else {
      // tables for each isolate - 
      var modaltables = {{modaltables | tojson}}; // jinja2 passing a list of tables
      var isolateid = selected[0];
      console.log(isolateid);
    //     need to set .modal-table to row with isolate id $('model-content').html(tablerow)
      $('.modal-title').html(isolateid + ' details');
      $('tr.' + isolateid).clone().appendTo('.modal-summary-table');
      // for each table in analysis generate a specific table
      $.each(modaltables, function(index, table){
        $('tr.' + isolateid + '-' + table).clone().appendTo('.modal-body-' + table);
      });      
      $("#myModal").modal();
  }
});

$("#change-tree").on("click", function (e) {
    var button_text = $(this).text();
    if (button_text == "Circular"){
        tree.setTreeType("circular");
        $(this).html("Rectangular");
    } else if (button_text == "Rectangular") {
        tree.setTreeType("rectangular");
        $(this).html("Circular");
    }
    
});



$("button.help").click(function(){
  $("#myModal3").modal();
});
// remove lines from table
$(function(){  
        $('#myModal').on('hidden.bs.modal', function (e) {
        var modaltables = {{modaltables | tojson}}; // jinja2 passing a list of tables
        console.log("Modal hidden");
        $('.modal-body-summary-table').html("");
        $.each(modaltables, function(index, table){
          $('.modal-body-' + table).html("");
        });
        
        });
});
$('table.summary-table').DataTable( {
      lengthMenu: [[10, 20, 40, 60, 80, 100 -1], [10, 20, 40, 60, 80, 100, "All"]],
      //scrollY: '50vh',
      scrollCollapse: true,
      paging: false,
      dom: 'Bfrtip',
        buttons: [
             'csv', 'excel'
        ],
//       order: [[ -1, "Isolate" ]],
    } );
$('table.detail-table').DataTable( {
        //lengthMenu: [[10, 20, 40, 60, 80, 100 -1], [10, 20, 40, 60, 80, 100, "All"]],
        //scrollY: '50vh',
      
        scrollCollapse: true,
        paging: false,
        dom: 'Bfrtip',
        buttons: [
             'csv', 'excel'
        ],
        // scrollX: true,
        //       order: [[ -1, "Isolate" ]],
        } );

// get the pairwise snps from tree tips


// put the selected table in the selected detail div
$('button.detail-button').click(function(){
        // use the id of the button to find the class of the table to be inserted
       
        var section = $(this).text().replace(/\s+/g, '-').toLowerCase();
        var modaltables = {{tables | tojson}}; // jinja2 passing a list of tables
        
        $.each(modaltables, function( index, value ){
          if (section == value){
            console.log('showing #' + value);
            $('#' + value).show(); 
          } else {
            console.log('hiding #' + value);
            $('#' + value).hide();
        }
         });
        
        var section = $(this).text().replace(/\s+/g, '-').toLowerCase();
        console.log(section);
        
        if (section == 'snp-distances'){
          // for snp-distances
            var x = {{snpdistances | tojson}};
            var max_x = Math.max(x);
            var bin_size = max_x / 100;
            var trace = {
                x: x,
                type: 'histogram',
                xbins : {
                  end:max_x,
                  size: bin_size,
                  start:0
                }
              };
            var layout = {
              xaxis:{
                title:"Distribution of pairwise SNP distances"
              },
              yaxis:{
                title:"Count"
              },
              
            };
            var data = [trace];
            Plotly.newPlot('snp-distances-graph', data, layout);
            // put selecte into current table
            //var selected = $('#' + section).html();
            console.log('showing #' + section);
            //$('#snp-distances').show();
            $('#snp-density-graph').html("");     
        } else if (section == 'core-genome'){
          // put snp-density in here
            var x = {{ snpdensity | tojson}};
            
            // var y = {{genomebreaks | safe}};
            var max_x = Math.max(x);
            var bin_size = max_x / 100;
            var trace = {
                x: x,
                type: 'histogram',
                xbins : {
                  end:max_x,
                  size: bin_size,
                  start:0
                }
              };
            var layout = {
              xaxis:{
                title:"Genome Position (MB)"
              },
              yaxis:{
                title:"Count"
              },
              // put lines in here
              
            };
            var data = [trace];
            Plotly.newPlot('snp-density-graph', data, layout);
            // put selecte into current table
            var selected = $('#' + section).html();
            //$('#' + section).show();  
            $('#snp-distances-graph').html("");      
        } else {
          var selected = $('#' + section).html();
          //$('#' + section).show();  
          $('#snp-distances-graph').html("");
          $('#snp-density-graph').html("");
        }
        
        });

}); 




// for showing snp-distances of selected isolates from tree 
var ds = new DragSelect({
selectables: document.getElementsByClassName('tiplab'),
area: document.getElementById('phylogeny'),
callback: function(elements) {
        var selected = [0];
        console.log(elements.length);
        if (elements.length > 1){
                $.each(elements, function( index, value ) {
                        var cols = $('#snp-distances th:contains(' + value.innerHTML + ')');
                        var index = cols.index();
                        selected.push(index);
                        });
                console.log(selected);
                var table_head = "<thead>\n<tr>\n";
                var table_body = "<tbody>";
                $.each(selected, function( index, row){
                        var body_row = "<tr>";
                        $.each(selected, function(index, cell){
                                // console.log(" row " + row + " cell " + cell);
                                console.log($('#snp-distances tr:eq('+row+')')[0].cells[cell].innerHTML);
                                
                                if (row == 0) {
                                        body_row = body_row + "<th>" + $('#snp-distances tr:eq('+row+')')[0].cells[cell].innerHTML + "</th>\n";
                                } else  {
                                        body_row = body_row + "<td>" + $('#snp-distances tr:eq('+row+')')[0].cells[cell].innerHTML + "</td>\n";
                                }
                        });
                        body_row = body_row ;
                        if (row == 0) {
                                table_head = table_head + body_row + "</tr></thead>\n";
                        } else {
                      
                                table_body = table_body + body_row + "</tr>";
                        }
                });
                table_body = table_body + "</tbody>";
                // console.log(table_head);
                // console.log(table_body);
                var t = table_head + table_body;
                $('.modal-selected-snps-table').html(t);
                $("#myModal2").modal();
        } 
},

}); 

</script>
{% endblock %}
<script>
feather.replace()
</script>
</body>
</html>