{% from 'attachments/_attachments.html' import get_attachment_icon, render_attachment %}

{% macro render_folder(folder) -%}
    <div class="folder {% if folder.is_self_protected %}is-protected{% endif %}">
        <div class="attachments group">
            <span class="i-button label" title="{{ folder.description }}">{{ folder.title }}</span>
            {% if folder.attachments|count <= 2 %}
                {%- for attachment in folder.attachments -%}
                    {{ render_attachment(attachment, has_label=true, classes='i-button') }}
                    {{ template_hook('event-display-after-attachment', attachment=attachment, top_level=true, has_label=true) }}
                {%- endfor -%}
            {% else %}
                <button class="i-button arrow" data-toggle="dropdown"></button>
                <ul class="i-dropdown">
                    {%- for attachment in folder.attachments -%}
                        {% set previewable = (attachment.file and attachment.file.is_previewable and not g.static_site) or false %}
                        {% set visible_link = attachment.type.name == 'link' and (not attachment.is_protected or attachment.can_access(session.user)) %}
                        <li>
                            <a data-previewable="{{ previewable | tojson }}"
                               data-attachment-id="{{ attachment.id }}"
                               href="{{ attachment.link_url if visible_link else attachment.download_url }}" target="_blank"
                               rel="noopener noreferrer"
                               class="attachment {{ get_attachment_icon(attachment) }}
                                      {%- if attachment.is_self_protected %} is-protected{% endif %}
                                      {%- if previewable %} js-preview-dialog{% endif %}">
                                {{- attachment.title -}}
                            </a>
                        </li>
                        {{ template_hook('event-display-after-attachment', attachment=attachment, top_level=false, has_label=false) }}
                    {%- endfor -%}
                </ul>
            {% endif %}
        </div>
    </div>
{%- endmacro %}

{% macro render_attachments_folders(item=none, files=[], folders=[]) %}
    {% set files = item.attached_items.get('files', []) if item else files %}
    {% set folders = item.attached_items.get('folders', []) if item else folders %}

    <div class="attachments-display-container toolbar">
        {% for attachment in files %}
            <div class="folder">
                {{ render_attachment(attachment, classes='i-button') }}
                {{ template_hook('event-display-after-attachment', attachment=attachment, top_level=true, has_label=false) }}
            </div>
        {% endfor %}

        {%- for folder in folders -%}
            {{ render_folder(folder) }}
        {%- endfor %}
    </div>
{% endmacro %}
