{% extends 'iconolab_base.html' %}

{% load staticfiles %}
{% load thumbnail %}
{% load iconolab_tags %}

{% block content_fluid %}

<div class="annotation-navigator">
  <div class="annotation-navigator-list">
    <div class="panel panel-default">
      {% if image.annotations.exists %}
        <div class="list-group">
        {% for annotation in image.latest_annotations %}
          <a href="#{{ annotation.annotation_guid }}" class="list-group-item"
            data-annotation-id="{{ annotation.annotation_guid }}"
            data-revision-id="{{ annotation.current_revision.revision_guid }}">
            <h3 class="small list-group-item-heading">
              {{ annotation.current_revision.title }}
              <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </h3>
            {% for tagging_info in annotation.current_revision.tagginginfo_set.all %}
            <p class="list-group-item-text">{{ tagging_info.tag.label }}</p>
            {% endfor %}
            <div class="list-group-item-footer">
              <i class="fa fa-comment"></i>
              {{ annotation.stats.comments_count }} commentaire{% if annotation.stats.comments_count > 1 %}s{% endif %}
            </div>
          </a>
        {% endfor %}
        </div>
      {% else %}
        <div class="panel-body">
          <div class="alert alert-warning text-center">Pas d'annotation pour cette image</div>
        </div>
      {% endif %}
    </div>
  </div>
  <div class="annotation-navigator-canvas">

    <image-annotator v-bind:annotation="annotation"
      ref="annotator"
      image="{% with image.media as img %}{{ img.url }}{% endwith %}"
      thumbnail="{% thumbnail image.media '100x100' crop=False as thumb %}{{ thumb.url }}{% endthumbnail %}"
      v-bind:is-authenticated="isAuthenticated"></image-annotator>

    <div>
      <dl class="dl-horizontal">
        {% if item.metadatas.designation %}<dt>Désignation</dt><dd>{{item.metadatas.designation}}</dd>{% endif %}
        {% if item.metadatas.authors %}<dt>Auteur(s)</dt><dd>{{item.metadatas.designation}}</dd>{% endif %}
        {% if item.metadatas.field %}<dt>Domaine</dt><dd>{{item.metadatas.field}}</dd>{% endif %}
        {% if item.metadatas.conservation_location %}<dt>Conservé à</dt><dd>{{item.metadatas.conservation_location}}</dd>{% endif %}
        {% if item.metadatas.datation %}<dt>Datation</dt><dd>{{item.metadatas.datation}}</dd>{% endif %}
        {% if item.metadatas.technics %}<dt>Techniques</dt><dd>{{item.metadatas.technics}}</dd>{% endif %}
        {% if item.metadatas.measurements %}<dt>Mesures : {{item.metadatas.measurements}}</h5>{% endif %}
        {% if item.metadatas.create_or_usage_location %}<dt>Lieu de création/utilisation</dt><dd>{{item.metadatas.create_or_usage_location}}</dd>{% endif %}
        {% if item.metadatas.discovery_context %}<dt>Contexte de découverte</dt><dd>{{item.metadatas.discovery_context}}</dd>{% endif %}
        {% if item.metadatas.photo_credits %}<dt>Crédits photographiques</dt><dd>{{item.metadatas.photo_credits}}</dd>{% endif %}
        {% if item.metadatas.inventory_number %}<dt>Numéro d'inventaire</dt><dd>{{item.metadatas.inventory_number}}</dd>{% endif %}
      </dl>
      {% if item.metadatas.joconde_ref %}
      <a href="{{item.metadatas.get_joconde_url}}" target="_blank">
      Cet objet dans Joconde, catalogue collectif des collections des musées de France
      </a>
      {% endif %}
    </div>

    <form id="form-annotation" action="{% url 'annotation_create' collection_name image.image_guid %}" method="POST">
      {% csrf_token %}
      <input type="hidden" name="{{ form.title.name }}">
      <input type="hidden" name="{{ form.description.name }}">
      <input type="hidden" name="{{ form.fragment.name }}">
      <input type="hidden" name="{{ form.tags.name }}">
    </form>
  </div>
  <div class="annotation-navigator-panel">
    <div class="panel panel-default">
      <div class="panel-body">
        <annotation-form v-bind:annotation="annotation"
          v-bind:is-authenticated="isAuthenticated"
          action="{% url 'annotation_edit' collection_name image_guid ':annotation_guid' %}">
          {% csrf_token %}
        </annotation-form>
        <div class="annotation-comment-box" id="form-comment">
          <comment-form v-if="annotation"></comment-form>
        </div>
        <div style="display: none;" class="annotation-comment-list">
          <label class="small text-muted">Commentaires</label>
          <comment-list v-bind:annotation="annotation"
            fetch="{% url 'get_annotation_comments_json' ':annotation_guid' %}"></comment-list>
        </div>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block footer_js %}
<script>

  var currentPath = "{{ request.path }}";
  var getCommentFormURL = "{% url 'get_comment_form' ':annotation_guid' %}"
  var isAuthenticated = {% if user.is_authenticated %}true{% else %}false{% endif %};

  Vue.component('comment-form', {
    template: '<div></div>',
    data: function() {
      return {
        replyTo: 0,
        btnGroupClass: {}
      }
    }
  });

  var vm = new Vue({
    el: '.annotation-navigator',
    data: function() {
      return {
        annotation: null,
        isAuthenticated: isAuthenticated
      };
    }
  });

  var annotations = {};
  {% if image.annotations %}
    {% for annotation in image.annotations.all %}
  annotations["{{ annotation.current_revision.revision_guid }}"] = {{ annotation.current_revision|json|safe }}
    {% endfor %}
  {% endif %}

  function displayAnnotation($el) {

    var annotation = $el.data('annotation-id');
    var revision = $el.data('revision-id');

    // Load the form for selected annotation via AJAX
    $.get(getCommentFormURL.replace(':annotation_guid', annotation), { next: currentPath + '#' + annotation })
      .then(function(form) {

        Vue.component('comment-form', function (resolve, reject) {
          resolve({
            props: ['reply-to'],
            template: form,
            data: function() {
              return {
                active: null
              }
            },
            watch: {
              active: function(active) {
                if (active) {
                  setTimeout(() => $(this.$el).find('[name="comment"]').focus(), 200);
                }
              }
            },
            computed: {
              btnGroupClass: function() {
                var classes = [
                  { active: this.active || false }
                ];

                if (this.active) {
                  classes.push('btn-group-' + this.active)
                }

                return classes;
              }
            }
          });
        });

        $('.list-group a[data-annotation-id]').removeClass('active');
        $el.addClass('active');

        $('.annotation-comment-list').show();

        vm.annotation = annotations[revision];

        location.hash = '#' + annotation;

      });
  }

  $('.list-group a[data-annotation-id]').on('click', function(e) {
    e.preventDefault();
    var $el = $(e.currentTarget);
    displayAnnotation($el);
  });

  vm.$refs.annotator.$on('save', function(data) {
    $('#form-annotation').find('input[name="title"]').val(data.title);
    $('#form-annotation').find('input[name="description"]').val(data.description);
    $('#form-annotation').find('input[name="fragment"]').val(data.fragment);

    var tags = data.tags.map(function(tag) {
      return {
        tag_input: (typeof tag.tag_link === "string" && tag.tag_link.length) ? tag.tag_link : tag.tag_label,
        tag_label: tag.tag_label,
        accuracy: tag.accuracy,
        relevancy: tag.relevancy
      }
    })
    $('#form-annotation').find('input[name="tags"]').val(JSON.stringify(tags));
    $('#form-annotation').submit();
  })

  $('.list-group a[data-annotation-id] .close').on('click', function(e) {
    e.preventDefault();
    e.stopPropagation();

    var $target = $(e.currentTarget);
    $target.closest('.list-group-item').removeClass('active');

    vm.annotation = null;

    $('.annotation-comment-list').hide();

    location.hash = '';
  });

  function scrollTo($container, $el) {
    $container.animate({
      scrollTop:  $container.scrollTop() - $container.offset().top + $el.offset().top
    }, 600);
  }

  function router (scroll) {
    var url = location.hash.slice(1);
    if (url.length) {
      var annotation = url;
      var $el = $('.list-group a[data-annotation-id="'+annotation+'"]');
      displayAnnotation($el);
      if (scroll) {
        scrollTo($el.closest('.panel'), $el); 
      }
    }
  }
  window.addEventListener('hashchange', function() { router(true) });
  window.addEventListener('load', function() { router(true) });

</script>
{% endblock %}
