{% extends "base.html" %}

{% block title %}{{ image.title }}{% endblock %}

{% block content %}
  <h1>{{ image.title }}</h1>
  {% load thumbnail %}
  <a href="{{ image.image.url }}">
    <img src="{% thumbnail image.image 300x0 %}" class="image-detail">
  </a>
  {% with total_likes=image.users_like.count users_like=image.users_like.all %}
    <div class="image-info">
      <div>
        <span class="count">
          <span class="total">{{ total_likes }}</span>
          polubień
        </span>
        <span class="count">
          {{ total_views }} wyświetleń
        </span>
        <a href="#" data-id="{{ image.id }}" data-action="{% if request.user in users_like %}nie{% endif %}lubię"
    class="like button">
          {% if request.user not in users_like %}
            Lubię
          {% else %}
            Nie lubię
          {% endif %}
        </a>
      </div>
      {{ image.description|linebreaks }}
    </div>
    <div class="image-likes">
      {% for user in users_like %}
        <div>
          {% if user.profile.photo %}
            <img src="{{ user.profile.photo.url }}">
          {% endif %}
          <p>{{ user.first_name }}</p>
        </div>
      {% empty %}
        Nikt jeszcze nie polubił obrazu.
      {% endfor %}
    </div>
  {% endwith %}
{% endblock %}

{% block domready %}
  const url = '{% url "images:like" %}';
  var options = {
    method: 'POST',
    headers: {'X-CSRFToken': csrftoken},
    mode: 'same-origin'
  }

  document.querySelector('a.like')
          .addEventListener('click', function(e){
    e.preventDefault();
    var likeButton = this;

    // dodanie treści żądania
    var formData = new FormData();
    formData.append('id', likeButton.dataset.id);
    formData.append('action', likeButton.dataset.action);
    options['body'] = formData;

    // wysłanie żądania HTTP
    fetch(url, options)
    .then(response => response.json())
    .then(data => {
      if (data['status'] === 'ok')
      {
        var previousAction = likeButton.dataset.action;

        // zmiana tekstu przycisku i operacji do wykonania 
        var action = previousAction === 'lubię' ? 'nie lubię' : 'lubię';
        likeButton.dataset.action = action;
        likeButton.innerHTML = action;

        // aktualizacja liczby polubień
        var likeCount = document.querySelector('span.count .total');
        var totalLikes = parseInt(likeCount.innerHTML);
        likeCount.innerHTML = previousAction === 'lubię' ? totalLikes + 1 : totalLikes - 1;
      }
    })
  });
{% endblock %}
