{% extends "layout_bs4.html" %}
{% from "variants/utils.html" import compounds_table, svs_table, snv_filters, cell_rank %}
{% from "variants/components.html" import gene_cell, frequency_cell %}

{% block title %}
  {{ super() }} - {{ institute.display_name }} - {{ case.display_name }} - {{ form.variant_type.data|capitalize }} variants
{% endblock %}

{% block css %}
{{ super() }}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.9/dist/css/bootstrap-select.min.css">
{% endblock %}

{% block top_nav %}
  {{ super() }}
  <li class="nav-item">
    <a class="nav-link text-nowrap" href="{{ url_for('cases.index') }}">Institutes</a>
  </li>
  <li class="nav-item">
    <a class="nav-link text-nowrap" href="{{ url_for('cases.cases', institute_id=institute._id) }}">
      {{ institute.display_name }}
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link text-nowrap" href="{{ url_for('cases.case', institute_id=institute._id, case_name=case.display_name) }}">
      {{ case.display_name }}
    </a>
  </li>
  <li class="nav-item active">
    <span class="navbar-text">{{ form.variant_type.data|capitalize }} SNV and INDELs</span>
  </li>
{% endblock %}

{% block top_nav_right %}
  <li class="nav-item text-nowrap"><p class="navbar-text">Panels: {{ (form.gene_panels.data or ['All'])|join(',') }}</p></li>
  {{ super() }}
{% endblock %}
{% block content_main %}
  <form method="POST" id="filters_form" action="{{url_for('variants.variants', institute_id=institute._id, case_name=case.display_name)}}"
    enctype="multipart/form-data" onsubmit="return validateForm()">
    <div class="container-float">
      <div class="card panel-default" id="accordion">
        <div class="card-header">
          <strong><a data-toggle="collapse" data-parent="#accordion" href="#collapseFilters">Filters</a></strong>
        </div>
        <div class="card-body panel-collapse collapse" id="collapseFilters">
            {{ snv_filters(form, institute, case) }}
        </div>
      </div>
      <div class="card mt-3">
        <table class="table table-hover table-bordered">
          <thead>
            <tr>
              <th style="width:8%" title="Rank position">Rank </th>
              <th style="width:8%" title="Rank score">Score</th>
              <th style="width:8%" title="Chromosome">Chr.</th>
              <th style="width:8%" title="HGNC symbols">Gene</th>
              <th style="width:8%" title="Poulation frequency">PopFreq</th>
              <th style="width:8%" title="CADD score">CADD</th>
              <th style="width:8%" title="Gene region annotation">Gene annotation</th>
              <th style="width:18%"" title="Functional annotation">Func. annotation</th>
              <th style="width:18%" title="Inheritance models">Inheritance model</th>
              <th style="width:8%"" title="Overlapping">Overlapping</th>
            </tr>
          </thead>
          <tbody>
            {% for variant in variants %}
              {% if variant.dismiss_variant %}
                <tr class="dismiss">
              {% else %}
                <tr>
              {% endif %}
                <td class="text-left">{{ cell_rank(variant, institute, case, form, manual_rank_options) }}</td>
                <td class="text-right">{{ variant.rank_score|int }}</td>
                <td>{{ variant.chromosome }}</td>
                <td>{{ gene_cell(variant) }}</td>
                <td class="text-right">{{ frequency_cell(variant) }}</td>
                <td class="text-right">{{ cell_cadd(variant) }}</td>
                <td>
                  {% for annotation in variant.region_annotations %}
                    <div>{{ annotation }}</div>
                  {% endfor %}
                </td>
                <td>
                  {% for annotation in variant.functional_annotations %}
                    <div>{{ annotation }}</div>
                  {% endfor %}
                </td>
                <td>{{ cell_models(variant) }}</td>
                <td>{{ overlapping_cell(variant) }}</td>
              </tr>
            {% else %}
              <tr>
                <td colspan="10">
                  No matching variants
                </td>
              </tr>
            {% endfor %}
          </tbody>
        </table>
      </div><!-- end of <div class="card mt-3">-->
    </div> <!-- end of class="container-float"> -->
      {{ footer() }}
  </form>
{% endblock %}

{% macro cell_cadd(variant) %}
  <div data-toggle="tooltip" data-placement="left" data-html="true" title="
    <div class='text-left'>
      <strong>Sift</strong>
      {{ variant.sift_predictions|join(',') }} <br>
      <strong>PolyPhen</strong>
      {{ (variant.polyphen_predictions or ['-'])|join(',') }}
    </div>
  ">
    {{ variant.cadd_score }}
  </div>
{% endmacro %}

{% macro cell_models(variant) %}
  {% for model in (variant.genetic_models or []) %}
    <span class="badge badge-secondary">{{ model }}</span>
  {% endfor %}

  {% if variant.compounds %}
    <a href="#" class="badge badge-primary text-white" data-toggle="popover" data-placement="left"
    data-html="true" data-trigger="hover click"
    data-content="{{ compounds_table(institute, case, variant.compounds[:20]) }}">Compounds</a>
  {% endif %}
  {% if variant.mosaic_tags %}
    <span class="badge badge-warning">mosaic</span>
  {% endif %}
{% endmacro %}

{% macro overlapping_cell(variant) %}
  {% if variant.overlapping %}
  <a href="#" class="badge badge-warning" data-toggle="popover" data-placement="left"
    data-html="true" data-trigger="hover click"
    data-content="{{ svs_table(institute, case, variant.overlapping[:20]) }}">Overlapping SVs</a>
  {% else %}
    -
  {% endif %}
{% endmacro %}

{% macro footer() %}
  <div class="container-fluid">
      {% if more_variants %}
        <div class="d-flex justify-content-around">
	         <div>
            <button name="page" type="submit" class="btn btn-outline-secondary mx-auto d-block" value=1>First page</button>
          </div>
          <div>
            <button name="page" type="submit" class="btn btn-outline-secondary mx-auto d-block" value={{ page + 1 }}>Next page</button>
          </div>
	     </div>
      {% else %}
        <i class="text-muted">No more variants to display</i>
        <button name="page" type="submit" class="btn btn-outline-secondary mx-auto d-block" value=1>First page</button>
      {% endif %}
  </div>
{% endmacro %}

{% block scripts %}
  {{ super() }}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/1.0.11/purify.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sticky-table-headers/0.1.19/js/jquery.stickytableheaders.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.9/dist/js/bootstrap-select.min.js"></script>
  <script>
    function validateForm(){
      var valid_chroms = [];
      i = 1;
      while(valid_chroms.push(i++) <22){};
      valid_chroms.push("X","Y","MT");
      var chrom = document.forms["filters_form"].elements["chrom"].value;
      if(chrom && !valid_chroms.map(String).includes(chrom)){
        alert("Chromosome field is not valid. Accepted values are: "+valid_chroms)
        return false
      }
      var start = document.forms["filters_form"].elements["start"].value
      var end = document.forms["filters_form"].elements["end"].value
      if(start || end){
        if(!chrom){
          alert("Chromosome field is required");
          return false;
        }
        else if( !start || !end){
          alert("Both start and end coordinates are required");
          return false;
        }
        else if( (isNaN(start) || isNaN(end)) || end<start ){
          alert("Coordinate field not valid");
          return false;
        }
      }
      return true;
    }

    $('select[multiple]').selectpicker({
      width: '100%'
    });

    $(function () {
      $('[data-toggle="tooltip"]').tooltip();
      $('[data-toggle="popover"]').popover({
        sanitizeFn: function (content) {
          return DOMPurify.sanitize(content)
        },
        container: 'body',
      });

      $('table').stickyTableHeaders({
        fixedOffset: $(".navbar-fixed-top")
      });

      document.getElementById('symbol_file').onchange = function() {
        var the_form = document.forms['filters_form'];
        the_form.submit();
      };
    });
  </script>
{% endblock %}
