{# Import this module with context:
   {% import "widgets/tag_selector.html" as widget_tag_selector with context %}
 This is necessary because it uses global names from context processors. #}

{% macro tag_selector(field) %}
  {% set all_tags = db_all_tags() %}

  {# When Javascript is disabled, we use the text field directly #}
  <div>
    <noscript>
      {{ field.label }}
      {% if field.description %}
        <div class="desc">{{ field.description }}</div>
      {% endif %}
      <div class="desc">
        Saisie sans Javascript: saisissez directement les noms techniques des
        tags, séparés par des virgules (eg. <code>calc.g90+e</code>).
      </div>
      {{ field() }}
      {% for error in field.errors %}
        <span class="msgerror">{{ error }}</span>
      {% endfor %}
    </noscript>
  </div>

  {# When Javascript is enabled, use a dynamic system where the user can add
     and remove tags with the mouse #}
  <div class="dynamic-tag-selector">
    <div>{{ field.label }}:
      <span class="tags-selected">
        {% for ctgy, tags in all_tags.items() %}
        {% for tag in tags %}
          <span class="tag tag-{{ ctgy }}" data-name="{{ tag.id }}"
            onclick="tag_selector_remove(tag_selector_find(this), '{{ tag.id }}')">{{ tag.pretty }}</span>
        {% endfor %}
        {% endfor %}
      </span>
    </div>
    {% if field.description %}
      <div class="desc">{{ field.description }}</div>
    {% endif %}
    {{ field(oninput="tag_selector_update(tag_selector_find(this))") }}
    {% for error in field.errors %}
      <span class="msgerror">{{ error }}</span>
    {% endfor %}

    <div>Tags disponibles :</div>
    {% for ctgy, tags in all_tags.items() %}
      <div class="tags-pool">
        {% for tag in tags %}
          <span class="tag tag-{{ ctgy }}" data-name="{{ tag.id }}"
            onclick="tag_selector_add(tag_selector_find(this), '{{ tag.id }}')">{{ tag.pretty }}</span>
        {% endfor %}
      </div>
    {% endfor %}
  </div>
{% endmacro %}
