{% extends "layout_bs4.html" %}

{% block title %}
  {{ super() }} - {{ institute.display_name }} - Cases
{% endblock %}

{% block top_nav %}
  {{ super() }}
  <li class="nav-item">
    <a class="nav-link" href="{{ url_for('cases.index') }}">Institutes</a>
  </li>
  <li class="nav-item active">
    <a class="nav-link" href="#">{{ institute.display_name }} Cases</a>
  </li>
  {% if config.SHOW_CAUSATIVES %}
    <li class="nav-item">
      <a class="nav-link" href="{{ url_for('cases.causatives', institute_id=institute._id) }}">Causatives</a>
    </li>
  {% endif %}
  <li class="nav-item">
    <a class="nav-link" href="{{ url_for('cases.gene_variants', institute_id=institute._id, variant_type=['clinical'], rank_score=15) }}">All SNVs and INDELs</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="{{ url_for('cases.clinvar_submissions', institute_id=institute._id) }}">Clinvar submissions</a>
  </li>
{% endblock %}

{% block content_main %}
<div class="container-float">
  <div class="card panel-default">
    <div class="card-body">
      {{ search_form() }}
    </div>
    <div class="card-footer text-center">
      Showing {{ limit if limit < found_cases else found_cases }} /  {{ nr_cases }} cases
    </div>
  </div>

  {% if sanger_unevaluated %}
    <div class="container alert alert-info alert-dismissible" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      {% if sanger_unevaluated|length > 1%}
      You have <strong>{{ sanger_unevaluated|length }}</strong> cases with Sanger validations to evaluate!
      {% else %}
      You have <strong>1</strong> case with Sanger validations to evaluate!&nbsp;
      {% endif %}
      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#evaluateModal">
        evaluate
      </button>

      <!-- Modal -->
      <div class="modal fade" id="evaluateModal" tabindex="-1" role="dialog" aria-labelledby="sangerModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="sangerModalLabel">Sanger validations to evaluate:</h5>
            </div>
            <div class="modal-body">
              <ul>
                {% for uneval_obj in sanger_unevaluated %}
                {% for case, var_list in uneval_obj.items() %}
                <li>
                  Case <strong><a href="{{ url_for('cases.case', institute_id=institute._id, case_name=case) }}" target="_blank">{{case}}</a></strong> ---> <strong>{{var_list|length}}</strong> variants:
                  <ul>
                    {% for var in var_list %}
                      <li><a href="{{ url_for('variant.variant', institute_id=institute._id, case_name=case, variant_id=var) }}" target="_blank">{{var}}</a></li>
                    {% endfor %}
                  </ul>
                </li>
                {% endfor %}
                {% endfor %}
              </ul>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  {% endif %}
  <div>
    {% set ordered_statuses = ['prioritized', 'inactive', 'active', 'archived', 'solved', ] -%}
    {% for status in ordered_statuses %}
      {% for group_name, case_group in cases %}
        {% if status == group_name and case_group|length > 0 %}
          <div class="table-responsive">{{ cases_table(group_name, case_group) }}</div>
        {% endif %}
      {% endfor %}
    {% endfor %}
  </div>
</div>

{% endblock %}

{% macro search_form() %}
  <form action="{{ url_for('cases.cases', institute_id=institute._id) }}" method="GET" accept-charset="utf-8">
    <div class="row">
      <div class="col-md-4 col-sm-4">
        <div class="input-group">
          <span class="input-group-addon">
            <span class="glyphicon glyphicon-search"></span>
          </span>
          <input type="search" class="form-control" value="{{ query if query }}" name="query" placeholder="search cases"
          data-toggle="tooltip" data-placement="right" data-html="true" title="
            <div class='text-left'>
              <u>Examples:</u><br>case_id=<strong>18201</strong>,
              HPO&nbsp;term=<strong>HP:0001166</strong>,
              synopsis=<strong>synopsis:epilepsy</strong>,
              panel=<strong>panel:NMD</strong>,
              status=<strong>status:active</strong>,
              phenotype&nbsp;group=<strong>PG:0100022</strong>,
              cohort=<strong>cohort:pedhep</strong>,
              similar&nbsp;case=<strong>similar:18201</strong>,
              gene_pinned=<strong>pinned:POT1</strong>,
              gene_causative=<strong>causative:POT1</strong>,
              assigned_user=<strong>Kent</strong>.<br><br>
              Use key without value to search for cases with missing info (<strong>HP:</strong>, <strong>PG:</strong>, <strong>synopsis:</strong>).
            </div>
          "></input>
        </div>
      </div>
      <div class="col-md-2 col-sm-2">
        <button type="submit" class="form-control">Search</button>
      </div>
      <div class="col-md-2 col-sm-2">
        <div class="number">
          <label>
              <input name="limit" type="number" step="100" class="form-control" placeholder="Limit" value={{limit}}>
          </label>
        </div>
      </div>
      <div class="col-md-2 col-sm-2">
        <div class="checkbox">
          <label>
            <input type="checkbox" name="skip_assigned" {% if skip_assigned %}checked{% endif %}> Hide assigned
          </label>
        </div>
      </div>
      <div class="col-md-2 col-sm-2">
        <div class="checkbox">
          <label>
            <input type="checkbox" name="is_research" {% if is_research %}checked{% endif %}> Hide non-research
          </label>
        </div>
      </div>
    </div>
  </form>
{% endmacro %}

{% macro cases_table(group_name, cases) %}
{% if sort_order == 'asc' %}
  {% set sort_option = 'desc'%}
{% else %}
  {% set sort_option = 'asc'%}
{% endif %}
<div class="card mt-3">
  <div class="card-body" style="padding: 0;">
    <table class="table table-hover table-bordered">
      <thead>
        <tr>
          <th style="width: 25%">{{ group_name|capitalize }} cases</th>
          <th style="width: 10%">Status <a href="" id="{{group_name}}_status" onclick="updateArgs('{{group_name}}','sort=status','{{sort_option}}');" class="badge" style="color:{{'black' if sort_by=='status' else 'grey'}};background-color:white;">
            <i class="fa fa-sort{{'-'+sort_order if sort_by=='status' }}" aria-hidden="true" data-toggle="tooltip" title="Sort cases by 'status'"></i>
          </a></th>
          <th style="width: 15%">Analysis date <a href="" id="{{group_name}}_analysis_date" onclick="updateArgs('{{group_name}}','sort=analysis_date','{{sort_option}}');" class="badge" style="color:{{'black' if sort_by=='analysis_date' else 'grey'}};background-color:white;">
            <i class="fa fa-sort{{'-'+sort_order if sort_by=='analysis_date' }}" aria-hidden="true" data-toggle="tooltip" title="Sort by analysis date"></i>
          </a></th>
          <th style="width: 20%">Link</th>
          <th style="width: 5%">Sequencing</th>
          <th style="width: 15%">Track <a href="" id="{{group_name}}_track" onclick="updateArgs('{{group_name}}','sort=track','{{sort_option}}');" class="badge" style="color:{{'black' if sort_by=='track' else 'grey'}};background-color:white;">
            <i class="fa fa-sort{{'-'+sort_order if sort_by=='track' }}" aria-hidden="true" data-toggle="tooltip" title="Sort by analysis track: Rare Disease, Cancer.."></i>
          </a></th>
          <th style="width: 10%">Clinvar</th>
        </tr>
      </thead>
      <tbody>
      {% for case in cases %}
        {{ case_row(case) }}
      {% else %}
          <tr>
            <td colspan="">No cases found.</td>
          </tr>
      {% endfor %}
      </tbody>
    </table>
  </div><!--end of card-body-->
</div>
{% endmacro %}


{% macro case_row(case) %}
  <tr class="{% if case.status == 'solved' %} bg-success{% endif %}">
    <td>
      <a href="{{ url_for('cases.case', institute_id=case.owner, case_name=case.display_name) }}">
        {{ case.display_name }}
      </a>
      {% if case.individuals|length > 1 %}
        <span class="badge badge-primary">
          {% for item in case.individuals %}
            <i class="fa fa-user"></i>
          {% endfor %}
        </span>
      {% endif %}
      {% for user in case.assignees %}
        <span class="badge badge-secondary">{{ user.name }}</span>
      {% endfor %}
      {% if case.needs_check %}
        <span class="badge badge-warning">decipher</span>
      {% endif %}
    </td>
    <td>
      <span class="badge badge-primary">{{ case.status }}</span>
      {% if case.is_migrated %}
        <span class="badge badge-primary">migrated</span>
      {% endif %}
    </td>
    <td class="d-flex justify-content-between align-items-center">
      {{ case.analysis_date.date() }}
      {% if case.rerun_requested %}
          <span class="badge badge-secondary">rerun pending</span>
      {% elif case.is_rerun %}
        <span class="badge badge-secondary">rerun</span>
      {% endif %}
    </td>
    <td>
      {% if case.is_research %}
        {% if case.vcf_files.vcf_snv %}
          <a href="{{ url_for('variants.variants', institute_id=case.owner, case_name=case.display_name, variant_type='research') }}">Research SNV and INDELs</a>
        {% elif case.vcf_files.vcf_cancer %}
          <a href="{{ url_for('variants.cancer_variants', institute_id=case.owner, case_name=case.display_name, variant_type='research') }}">Clinical cancer variants</a>
        {% endif %}
      {% else %}
        {% if case.vcf_files.vcf_snv %}
          <a href="{{ url_for('variants.variants', institute_id=case.owner, case_name=case.display_name, variant_type='clinical', gene_panels=case.panels|selectattr('is_default')|map(attribute='panel_name')|list) }}">Clinical SNV and INDELs</a>
        {% elif case.vcf_files.vcf_cancer %}
          <a href="{{ url_for('variants.cancer_variants', institute_id=case.owner, case_name=case.display_name, variant_type='clinical') }}">Clinical cancer variants</a>
        {% elif case.vcf_files.vcf_cancer_sv %}
          <a href="{{ url_for('variants.cancer_sv_variants', institute_id=case.owner, case_name=case.display_name, variant_type='clinical') }}">Clinical cancer structural variants</a>
        {% endif %}
      {% endif %}
    </td>
    <td>
      {% for analysis_type in case.analysis_types %}
        {% if analysis_type == 'wgs' %}
          {% set badge_class = 'primary' %}
        {% elif analysis_type == 'wes' %}
          {% set badge_class = 'warning' %}
        {% elif analysis_type == 'tga' %}
          {% set badge_class = 'info' %}
        {% elif analysis_type == 'panel' %}
          {% set badge_class = 'info' %}
        {% elif analysis_type == 'mixed' %}
          {% set badge_class = 'mixed' %}
        {% elif analysis_type == 'external' %}
          {% set badge_class = 'danger' %}
        {% else %}
          {% set badge_class = 'default' %}
        {% endif %}

        <span class="badge badge-{{ badge_class }}">
          {{ analysis_type|upper }}
        </span>
      {% endfor %}
    </td>
    <td>
      {{ case.display_track }}
    </td>
    <td>
      {% if case.clinvar_variants %}
        <a href="#clinvar_{{case.display_name}}" data-toggle="modal">{{case.clinvar_variants|length}} {% if case.clinvar_variants|length >1 %} variants {% else %} variant {% endif %}</a>
        <!-- Modal -->
        <div class="modal fade" id="clinvar_{{case.display_name}}" tabindex="-1" role="dialog" aria-labelledby="variantModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="variantModalLabel">Variants included in Clinvar submissions:</h5>
              </div>
              <div class="modal-body">
                <ul>
                  {% for varname, clinvar in case.clinvar_variants.items() %}
                    <li>
                    {% if clinvar.category == 'snv' %}
                      <a href="{{ url_for('variant.variant', institute_id=case.owner, case_name=case.display_name, variant_id=clinvar.local_id) }}" target="_blank">chr{{clinvar.chromosome}}:{{clinvar.start}}_{{clinvar.ref}}>{{clinvar.alt}}</a>
                    {% else %}
                      <a href="{{ url_for('variant.sv_variant', institute_id=case.owner, case_name=case.display_name, variant_id=clinvar.local_id) }}" target="_blank">chr{{clinvar.chromosome}}:{{clinvar.breakpoint1}}_{{clinvar.var_type}}</a>
                    {% endif %}
                    </li>
                  {% endfor %}
                </ul>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              </div>
            </div>
          </div>
        </div>
      {% endif %}
    </td>
  </tr>
{% endmacro %}

{% block scripts %}
  {{ super() }}

  <script src="https://cdnjs.cloudflare.com/ajax/libs/sticky-table-headers/0.1.19/js/jquery.stickytableheaders.min.js"></script>
  <script>
    $(function () {
      $('[data-toggle="tooltip"]').tooltip();
      $('table').stickyTableHeaders({
        fixedOffset: $(".navbar-fixed-top")
      });
    });

    function updateArgs(caseGroup, sortItem, sortOrder) {
      sort_items = ['sort=status', 'sort=analysis_date', 'sort=track', 'order=asc', 'order=desc'];
      //modifying the sorting of cases
      let searchList = window.location.search.split('&');
      if(!searchList[0]){
        //fix url if sorting is the only param
        searchList[0] = '?';
      }
      //remove all sort params
      searchList = searchList.filter(f => !sort_items.includes(f))
      //add specific sort param
      searchList.push(sortItem);
      searchList.push("order="+sortOrder)

      sort_link = document.getElementById( caseGroup.concat('_',sortItem.split('=')[1]));
      const url = window.location.href.split('?')[0].concat(searchList.join('&'));
      sort_link.href = url;
      //submit link
      sort_link.submit();
    }

  </script>
{% endblock %}
