{% extends "base.html" %}
{% load thumbnail %} 
{% block title %}{{ user.get_full_name }}{% endblock %}

{% block content %}
  <h1>{{ user.get_full_name }}</h1>
  <div class="profile-info">
    <img src="{% thumbnail user.profile.photo 180x180 %}" class="user-detail">
  </div>
  {% with total_followers=user.followers.count %}
    <span class="count">
      <span class="total">{{ total_followers }}</span>
      obserwujących
     </span>
     <a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}nie {% endif %}obserwuj" class="follow button">
      {% if request.user not in user.followers.all %}
        Obserwuj
      {% else %}
        Nie obserwuj
      {% endif %}
    </a>
    <div id="image-list" class="image-container"> 
      {% include "images/image/list_images.html" with images=user.images_created.all %}
    </div>
  {% endwith %}
{% endblock %}

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

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

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

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

        //  przełączenie tekstu przycisku i działania data-action
        var action = previousAction === 'obserwuj' ? 'nie obserwuj' : 'obserwuj';
        followButton.dataset.action = action;
        followButton.innerHTML = action;

        // aktualizacja liczby obserwujących
        var followerCount = document.querySelector('span.count .total');
        var totalFollowers = parseInt(followerCount.innerHTML);
        followerCount.innerHTML = previousAction === 'obserwuj' ? totalFollowers + 1 : totalFollowers - 1;
      }
    })
  });
{% endblock %}

