{% extends 'iconolab_base.html' %}

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

{% block content %}

{% if messages %}
  {% for message in messages %}
  <div class="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>
    {{ message }}
  </div>
  {% endfor %}
{% endif %}

<div class="annotation-navigator">
  <div class="annotation-navigator-list">
    <div class="panel panel-default">
      {% if image.annotations.exists %}
        <annotation-list
          v-bind:annotations="annotations"
          v-bind:annotation="annotation"
          annotation-url="{% url 'annotation_detail' collection_name image_guid ':annotation_guid' %}"
          v-on:click:annotation="onAnnotationClick($event)"
          v-on:close:annotation="onAnnotationClose"><annotation-list>
      {% 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 %}"
      login-url="{% url 'account:login' %}?next={{ request.path | urlencode }}"
      v-bind:is-authenticated="isAuthenticated"
      v-bind:annotations="annotations"
      v-on:click:annotation="onAnnotationClick($event)"
      v-on:close:annotation="onAnnotationClose"></image-annotator>
    <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 &amp;&amp; isAuthenticated"></comment-form>
        </div>
        <div v-show="annotation" style="display: none;" class="annotation-comment-list">
          <label class="small text-muted">Commentaires</label>
          <comment-list v-bind:annotation="annotation"
            v-bind:is-authenticated="isAuthenticated"
            fetch="{% url 'get_annotation_comments_json' ':annotation_guid' %}"></comment-list>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="annotation-navigator-metadata">
  <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 %}
  <p class="text-center">
    <a href="{{item.metadatas.get_joconde_url}}" target="_blank">
    Cet objet dans Joconde, catalogue collectif des collections des musées de France
    </a>
  </p>
  {% endif %}
</div>

{% endblock %}

{% block footer_js %}
<script>

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

  window.onpopstate = function(event) {
    if (event.state.annotation_guid) {
      vm.annotation = getAnnotationByGuid(event.state.annotation_guid);
    } else {
      vm.annotation = null;
    }
  };

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

  var annotations = [];
  {% if image.annotations.exists %}
    {% for annotation in image.latest_annotations %}
  annotations.push({{ annotation.current_revision|json|safe }});
    {% endfor %}
  {% endif %}

  {% if annotation %}
  var annotation = getAnnotationByGuid("{{ annotation.annotation_guid }}");
  {% else %}
  var annotation = null;
  {% endif %}

  if (annotation) {
    getCommentForm(annotation).then(function(template) {
      updateCommentFormComponent(template);
      createViewModel();
    });
  } else {
    createViewModel();
  }

  var vm;
  function createViewModel() {

    vm = new Vue({
      el: '.annotation-navigator',
      data: function() {
        return {
          annotations: annotations,
          annotation: annotation,
          isAuthenticated: isAuthenticated,
        };
      },
      methods: {
        onAnnotationClick: function(annotation) {
          var self = this;
          getCommentForm(annotation).then(function(template) {
            updateCommentFormComponent(template);
            self.annotation = annotation;
            history.pushState({ annotation_guid: annotation.annotation_guid }, '', annotationURL.replace(':annotation_guid', annotation.annotation_guid));
          });
        },
        onAnnotationClose: function() {
          this.annotation = null;
          history.pushState({ annotation_guid: null }, '', imageURL);
        }
      }
    });

    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();
    })

  }

  function updateCommentFormComponent(template) {
    Vue.component('comment-form', function (resolve, reject) {
      resolve({
        props: ['reply-to'],
        template: template,
        data: function() {
          return {
            active: null,
            placeholder: 'Ajouter mon commentaire…'
          }
        },
        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;
          }
        },
        methods: {
          setActive: function(active, placeholder) {
            Object.assign(this, {
              active: active,
              placeholder: placeholder || 'Ajouter mon commentaire…'
            });
          }
        }
      });
    });
  }

  function getCommentForm(annotation) {
    return $.get(getCommentFormURL.replace(':annotation_guid', annotation.annotation_guid), {
      next: annotationURL.replace(':annotation_guid', annotation.annotation_guid)
    })
  }

  function getAnnotationByGuid(guid) {
    return _.find(annotations, function(annotation) {
      return annotation.annotation_guid === guid;
    });
  }

</script>
{% endblock %}
