{% extends "layout_bs4.html" %}
{% from "variants/utils.html" import compounds_table, svs_table, snv_filters, cell_rank, pagination_footer, pagination_hidden_div, dismiss_variants_block, filter_form_footer, mark_heteroplasmic_mt %}
{% 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('overview.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 %}
    <div class="container-float">
      <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()">
         {{ pagination_hidden_div(page) }}
        <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>
          <!--Expand filters form if filters were used in a previous POST request-->
          <div class="card-body panel-collapse collapse {{ 'show' if expand_search is sameas true }}" id="collapseFilters">
              {{ snv_filters(form, institute, case) }}
          </div>
          {{ filter_form_footer(form, result_size, total_variants, more_variants, page, variants|length) }}
        </div>

      <div class="card mt-3">
        <table class="table table-hover table-bordered" style="table-layout: fixed">
          <thead>
            <tr>
              <th style="width:3%"></th>
              <th style="width:12%" title="Rank position">Rank </th>
              <th style="width:6%" title="Rank score">Score</th>
              <th style="width:6%" title="Chromosome">Chr.</th>
              <th style="width:8%" title="HGNC symbols">Gene</th>
              <th style="width:6%" title="Poulation frequency">Pop Freq</th>
              <th style="width:6%" 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">
              {% elif variant._id in case.causatives %}
                <tr class="causative">
              {% else %}
                <tr>
              {% endif %}
                <td><input type="checkbox" value="{{variant._id}}" name="dismiss" onclick="enableDismiss()"></td>
                <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 }}
                  {% if variant.chromosome in ["MT","M"] %}
                    {{ mark_heteroplasmic_mt(case.individuals, variant.samples) }}
                  {% endif %}
		            </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>
        {{ dismiss_variants_block(dismiss_variant_options, institute, case) }}
      </div><!-- end of <div class="card mt-3">-->
    </form> <!--end of form containing filters and variants' table elements -->
    </div> <!-- end of class="container-float"> -->
    <div class="container-fluid">
      {{ pagination_footer(more_variants, page) }}
    </div>
{% 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>
  ">
    {% if variant.cadd_score %}
      {{ variant.cadd_score|round(1) }}
    {% else %}
      -
    {% endif %}
  </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 %}

{% 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 src="{{ url_for('variants.static', filename='form_scripts.js') }}"></script>
  <script type="text/javascript">

    var startElem = document.getElementById("start");
    var endElem = document.getElementById("end");
    var coords=[startElem,endElem];

    coords.forEach(function (item, index) {
      item.addEventListener("input", function() {
      eraseChromPosString()});
    });

    var chromSel = document.getElementById("chrom");
    chromSel.addEventListener("change", function() {
      populateCytobands({{cytobands|safe}});
    });

    var chromPosInpt = document.getElementById("chrom_pos");
    chromPosInpt.addEventListener("change", function() {
      populateCytobands({{cytobands|safe}});
    })

   chromPosInpt.addEventListener("input", function() {
      updateCoordinateFields(event.target)
   })

    var cytoStart = document.getElementById("cytoband_start");
    initSearchConstraints(cytoStart, startElem)

    var cytoEnd = document.getElementById("cytoband_end");
    initSearchConstraints(cytoEnd, endElem)

    window.onload=function() {
      populateCytobands({{cytobands|safe}});
    }

    $('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('hide_dismissed').onchange = function() {
        document.getElementById('expand_search').value = "False";
        var the_form = document.forms['filters_form'];
        the_form.submit();
      };

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