{% from "variants/utils.html" import tier_cell %}

{% macro beacon_modal(case) %}
<form method="POST" action="{{url_for('cases.beacon_submit')}}">
<div class="modal fade" id="beacon_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Beacon submission</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
          {% if not "beacon" in case %}
            <!-- form to submit variants to beacon -->
            <input type="hidden" name="case" value="{{case._id}}">

            <!--Sample selection-->
            <div class="row d-flex justify-content-center">
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" id="sampleradio1" name="samples" value="affected" checked>
                <label class="form-check-label" for="sampleradio1">
                  Affected individuals
                </label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" id="sampleradio2" name="samples" value="all">
                <label class="form-check-label" for="sampleradio2">
                  All individuals
                </label>
              </div>
            </div>

            <!--VCF files (variant type) selection-->
            <div class="row d-flex justify-content-around align-items-center mt-3">
              <label class="form-check-label" for="vcfselect">
                Variants type:
              </label>
              <select multiple name="vcf_files" id="vcfselect" class="selectpicker" data-width="70%">>
                {% for file, path in case.vcf_files.items() %}
                  {% if path and file in ["vcf_snv", "vcf_cancer", "vcf_snv_research", "vcf_cancer_research"] %} <!-- support for sharing SNVs for now -->
                    <option value="{{file}}" {{ "selected" if "research" not in file }}>{{file|replace("vcf_", "")|replace("_", " ")|upper}}</option>
                  {% endif %}
                {% endfor %}
              </select>
            </div>

            <!--Gene panel selection-->
            <div class="row d-flex justify-content-around align-items-center mt-3">
              <label class="form-check-label" for="vcfselect">
                Filter by panel:
              </label>
              <select multiple name="panels" id="panelselect" class="selectpicker" data-width="70%">>
                {% for panel in case.panels %}
                  <option value="{{panel.panel_id}}" {{ "selected" if panel.is_default }}>{{ panel.display_name|truncate(30, True) }} {{ panel.version }} ({{ panel.nr_genes }} genes)</option>
                {% endfor %}
              </select>
            </div>
          <!-- end of form to submit variants to beacon -->
          <!-- case variants are already in beacon, display info -->
          {% else %}
            <div class="d-flex justify-content-center">
              <table class="table table-sm">
                <tbody>
                  <tr>
                    <td><strong>Created date</strong></td>
                    <td>{{case.beacon.created_at.strftime('%Y-%m-%d %H:%M:%S')}}</td>
                  </tr>
                  <tr>
                    <td><strong>Created by</strong></td>
                    <td>{{case.beacon.user}}</td>
                  </tr>
                  <tr>
                    <td><strong>VCF samples</strong></td>
                    <td>{{ case.beacon.samples|join(", ") }}</td>
                  </tr>
                  <tr>
                    <td><strong>VCF filter</strong></td>
                    <td>{{ "gene panels" if case.beacon.panels|length > 0 else "entire VCF" }}</td>
                  </tr>
                  <tr>
                    <td><strong>VCF types</strong></td>
                    <td>{{ case.beacon.vcf_files|join(", ") }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          {% endif %}
      </div>
      <div class="modal-footer d-flex justify-content-around">
        <div>
          {% if case.beacon %}
            <a href="{{url_for('cases.beacon_remove', case_id=case._id)}}" class="btn btn-danger text-white">Remove all case variants from Beacon</a>
          {% else %}
            <button type="submit" class="btn btn-primary">Add variants to beacon</button>
          {% endif %}
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</div>
</form>
{% endmacro %}

{% macro variant_transcripts(gene) %}
<!-- Used in case_report template. Populate a table div with gene transcripts that are canonical, primary (max 5) or disease-associated -->
  {% set n_primary_txs = namespace(count=0) %}
  <ul>
    {% for transcript in gene.transcripts %}
      <!-- increase counter if it has associated refseq -->
      {% if transcript.refseq_identifiers %}
        {% set n_primary_txs.count = n_primary_txs.count + 1 %}
      {% endif %}

        <!-- show transcript info only if it's canonical, disease-associated or primary (print max 5 primary transcripts) -->
      {% if transcript.refseq_identifiers and n_primary_txs.count <= 5 or transcript.is_canonical or transcript.is_disease_associated or transcript.is_primary %}
        <li>{{transcript.transcript_id}}, RefSeq:[{{ transcript.refseq_identifiers|join(", ") or "-" }}], {{ (transcript.coding_sequence_name or '')|truncate(20, True) }},  {{ (transcript.protein_sequence_name or '')|truncate(20, True) }}
          {% if transcript.is_canonical %}
            <span class="badge badge-pill badge-info" title="canonical">C</span>
          {% endif %}
          {% if transcript.is_disease_associated %}
            <span class="badge badge-pill badge-danger" title="disease_associated">D</span>
          {% endif %}
          {% if transcript.is_primary %}
            <span class="badge badge-pill badge-primary" title="primary_ref_transcript">hgnc primary:{{transcript.refseq_id}}</span>
          {% endif %}
        </li>
      {% endif %}

    {% endfor %} <!-- end of { for transcript in gene.transcripts } loop -->
  </ul>
  {% if n_primary_txs.count > 5 %}
  .. other transcripts available for this variant are not shown.<br><br>
  {% endif %}

{% endmacro %}

{% macro pretty_link_variant(variant, case) %}
{# Returns human readable links to the corresponding variant page #}

  <a href="{{ url_for('variant.variant',
                   institute_id=variant.institute,
                   case_name=case.display_name,
                   variant_id=variant._id) }}">
  {% if variant.category in "str" %}
  {{ variant.str_repid }} {{ variant.alternative }}
  {% elif variant.category in ("snv", "cancer") %}
  {% set display_genes = [] %}
    {% for gene in variant.genes %}
      {% if gene.hgvs_identifier and gene.hgnc_symbol  %}
        {{ "" if display_genes.append(gene.hgnc_symbol + ' ' + gene.hgvs_identifier) }}
      {% elif gene.hgnc_symbol %}
          {{ "" if display_genes.append(gene.hgnc_symbol) }}
      {% elif gene.hgvs_identifier and gene.hgnc_id %}
          {{ "" if display_genes.append( gene.hgnc_id|string + ' ' + gene.hgvs_identifier) }}
      {% endif %}
    {% endfor %}

    {% if not display_genes %}
        {{ "" if display_genes.append( variant.simple_id ) }}
    {% endif %}

    {{ display_genes|join(", ") }}
  {% else %}
  <a href="{{ url_for('variant.sv_variant',
                            institute_id=variant.institute,
                            case_name=case.display_name,
                            variant_id=variant._id) }}">
  {{ variant.sub_category|upper }}({{ variant.chromosome }}{{ variant.cytoband_start }}-{{ variant.chromosome }}{{ variant.cytoband_end }})
  {% endif %}
  </a>
{% endmacro %}

{% macro causatives_list(causatives, partial_causatives, institute, case) %}
  <div class="card panel-default">
    <div data-toggle='tooltip' class="panel-heading" title="Displays all variants that have been marked causative for this case">
      <span class="fa fa-medkit"></span>&nbsp;
      Causative variants
    </div>
    <div class="card-body">
    <ul class="list-group">
      {% for variant in causatives %}
        <li class="list-group-item">
          {% if variant._id %}
            <div class="row align-items-between align-items-center">
              <div class="col">
                <i class="fa fa-check-circle-o"></i>
                {{ pretty_link_variant(variant, case) }}
                {% if variant.sanger_ordered and not variant.validation in ['True positive','False positive'] %}
                  <span class="badge badge-default">Verification ordered</span>
                {% elif variant.sanger_ordered %}
                  <span class="badge badge-success">Validated</span>
                {% endif %}
              </div>
              {% if variant.tumor %}
                {{ allele_div(variant.tumor, "Tumor") }}
              {% endif %}
              {% if variant.normal %}
                {{ allele_div(variant.normal, "Normal") }}
              {% endif %}
              <div class="col-1">
                {{ remove_form(url_for('cases.mark_causative',
                                       institute_id=institute._id,
                                       case_name=case.display_name,
                                       variant_id=variant._id,
                                       partial_causative=False),
                               button_name='action', button_value='DELETE') }}
              </div>
            </div>
          {% else %} <!-- no variant._id -->
            {{ variant }} <small class="text-muted">(not loaded)</small>
          {% endif %}
        </li>
      {% endfor %}
      <!-- End of causative variants -->
      <!-- Partial causative variants -->
      {% for variant_phenotypes in partial_causatives %}
        {% set variant = variant_phenotypes.variant %}
        <div class="list-group-item">
          {% if variant._id %}
            <div class="row align-items-between align-items-center">
              <div class="col">
                <i class="fa fa-check-circle-o"></i>
                {% if variant.category == "snv" %}
                  <a href="{{ url_for('variant.variant',
                                      institute_id=variant.institute,
                                      case_name=case.display_name,
                                      variant_id=variant._id) }}">
                        {{ variant.hgnc_symbols|join(', ') }} (partial causative)
		             {% else %}
        		      <a href="{{ url_for('variant.sv_variant',
                                            institute_id=variant.institute,
                                            case_name=case.display_name,
                                            variant_id=variant._id) }}">
		              {{ variant.sub_category|upper }}({{ variant.chromosome }}{{ variant.cytoband_start }}-{{ variant.chromosome }}{{ variant.cytoband_end }})
                  (partial causative)
		             {% endif %}
                 </a>
              </div>
              <div class="col-2">
                {{ remove_form(url_for('cases.mark_causative',
                                       institute_id=institute._id,
                                       case_name=case.display_name,
                                       variant_id=variant._id,
                                       partial_causative=True),
                               button_name='action', button_value='DELETE') }}
              </div>
            </div>
            <div class="row">
              <div class="col-4">
                OMIM diagnoses
              </div>
              <div class="col-8">
                {% for omim in variant_phenotypes.omim_terms %}
                  <span class="badge badge-sm badge-secondary">
                    <a class="text-white" target="_blank" href="http://omim.org/entry/{{omim}}">
                      {{omim}}
                    </a>
                  </span>
                {% endfor %}
              </div>
            </div>
            <div class="row">
              <div class="col-4">
                HPO terms
              </div>
              <div class="col-8">
                {% for hpo in variant_phenotypes.hpo_terms %}
                  <a class="text-white" target="_blank" href="http://hpo.jax.org/app/browse/term/{{hpo.phenotype_id}}">
                    <span class="badge badge-sm badge-info">{{hpo.phenotype_id}}</span>
                  </a>

                {% endfor %}
              </div>
            </div>

          {% else %}
            {{ variant }} <small class="text-muted">(not loaded)</small>
          {% endif %}
        </div>
      {% endfor %}
      <!-- end of partial causative variants -->
      {% if not case.causatives|length and not case.partial_causatives|length %}
        No variants marked causative
      {% endif %}
    </ul>
    </div>
  </div>
{% endmacro %}

{% macro allele_div(allele, type) %}
  {% if 'alt_freq' in allele %}
    <div class="col-1.5" data-toggle="tooltip" data-placement="top" title="{{ type }} alternative AF ">
      <div style="padding: 0 15px">{{ allele.alt_freq|round(4) }}</div>
    </div>
  {% endif %}
{% endmacro %}

{% macro suspects_list(suspects, institute, case, manual_rank_options, cancer_tier_options) %}
  <div class="card panel-default">
    <div data-toggle='tooltip' class="panel-heading panel-heading-secondary"
         title="Displays all variants that has been pinned for this case">
      <span class="fa fa-map-pin"></span>&nbsp;Pinned variants
    </div>
    <div class="card-body">
    <ul class="list-group">
      {% for variant in suspects %}
        <li class="list-group-item">
          {% if variant._id %}
            <div class="row">
              <div class="col">
                <div class="form-group row align-items-center">
                  <div class="ml-3">
                    <i class="fa fa-bookmark"></i>
                      {{ pretty_link_variant(variant, case) }}
                  </div>
                  <div style="padding: 0 10px 3px">
                  {% if variant.sanger_ordered and not variant.validation in ['True positive','False positive'] %}
                    <span class="badge badge-default">Verification ordered</span>
                  {% elif variant.sanger_ordered %}
                    <span class="badge badge-success">Validated</span>
                  {% elif variant.manual_rank or variant.cancer_tier %}
                    {{ tier_cell(variant, manual_rank_options, cancer_tier_options) }}
                  {% endif %}
                  {% if variant.mosaic_tags %}
                    <span class="badge badge-info">mosaic</span>
                  {% endif %}
                  </div>
                </div>
              </div>
              {% if variant.tumor %}
                {{ allele_div(variant.tumor, "Tumor") }}
              {% endif %}
              {% if variant.normal %}
                {{ allele_div(variant.normal, "Normal") }}
              {% endif %}
              <div class="col-3.5">
              <form action="{{ url_for('cases.mark_validation',
                                         institute_id=variant.institute,
                                         case_name=case.display_name,
                                         variant_id=variant._id) }}"
                      method="POST" accept-charset="utf-8">
                  <select class="form-control form-control-sm" onchange="this.form.submit()" name="type">
                    {% for type in ('Not validated', 'True positive', 'False positive') %}
                      <option value="{{ type }}" {% if type == variant.validation %}selected{% endif %}>{{ type }}</option>
                    {% endfor %}
                  </select>
                </form>
              </div>
            <div class="col-1">
              {{ remove_form(url_for('cases.pin_variant',
                                     institute_id=institute._id,
                                     case_name=case.display_name,
                                     variant_id=variant._id),
                             button_name='action', button_value='DELETE') }}
            </div>
          </div>
          {% else %}
            {{ variant }} <small class="text-muted">(not loaded)</small>
          {% endif %}
        </li>
      {% endfor %}
      {% if not suspects|length %}
        No pinned variants
      {% endif %}
    </ul>
    </div>
  </div>
{% endmacro %}

{% macro matching_causatives(other_causatives, institute, case) %}
  <div class="card panel-default" >
    <div data-toggle='tooltip' class="panel-heading" title="If there are any variants in this case
      that have been marked as causative in another case for this insitute">
      <strong><a data-toggle="collapse" href="#matchingCausatives" class="text-white">Matching causatives from other cases ({{other_causatives|length}})</a></strong>
    </div>
    <ul class="list-group collapse" id="matchingCausatives">
      {% for variant in other_causatives %}
        <li class="list-group-item">
          <a href="{{ url_for('variant.variant', institute_id=institute._id,
                              case_name=case.display_name, variant_id=variant._id) }}">
            {{ variant.hgnc_symbols|join(', ') or variant.hgnc_ids|join(', ')}}
          </a>
        </li>
      {% else %}
        <li class="list-group-item">No matching causative variants.</li>
      {% endfor %}
    </ul>
  </div>
{% endmacro %}

{% macro matching_managed_variants(managed_variants, institute, case) %}
  <div class="card panel-default">
    <div data-toggle='tooltip' class="panel-heading" title="Any variants in this case
      that have been marked as managed">
      <strong><a data-toggle="collapse" href="#matchingManaged" class="text-white">Managed variants ({{managed_variants|length}})</a></strong>
    </div>
    <ul class="list-group">
      {% for variant in managed_variants %}
        <li class="list-group-item collapse" id="matchingManaged">
          <a href="{{ url_for('variant.variant', institute_id=institute._id,
                              case_name=case.display_name, variant_id=variant._id) }}">
            {{ variant.hgnc_symbols|join(', ') }}
          </a>
        </li>
      {% else %}
        <li class="list-group-item">No managed variants.</li>
      {% endfor %}
    </ul>
  </div>
{% endmacro %}


{% macro remove_form(url, hidden_input=None, button_name=None, button_value=None) %}
  <form action="{{ url }}" method="POST">
    {% if hidden_input %}
      <input type="hidden"
             name="{{ hidden_input[0] }}"
             value="{{ hidden_input[1] }}">
    {% endif %}
    <div class="pull-right">
      <button class="btn btn-link btn-sm"
              name="{{ button_name if button_name }}"
              value="{{ button_value if button_value }}"
              type="submit">
        <i class="fa fa-remove"></i>
      </button>
    </div>
  </form>
{% endmacro %}
