{% extends "forms/field.html.twig" %}

{% macro bytesToSize(bytes) -%}
{% apply spaceless %}
        {% set kilobyte = 1024 %}
        {% set megabyte = kilobyte * 1024 %}
        {% set gigabyte = megabyte * 1024 %}
        {% set terabyte = gigabyte * 1024 %}

        {% if bytes < kilobyte %}
            {{ bytes ~ ' B' }}
        {% elseif bytes < megabyte %}
            {{ (bytes / kilobyte)|number_format(2, '.') ~ ' KB' }}
        {% elseif bytes < gigabyte %}
            {{ (bytes / megabyte)|number_format(2, '.') ~ ' MB' }}
        {% elseif bytes < terabyte %}
            {{ (bytes / gigabyte)|number_format(2, '.') ~ ' GB' }}
        {% else %}
            {{ (bytes / terabyte)|number_format(2, '.') ~ ' TB' }}
        {% endif %}
    {% endapply %}
{%- endmacro %}

{% macro preview(path, value, global) %}
    {% if value %}
        {% set uri = global.grav.uri %}
        {% set files = global.files %}
        {% set config = global.grav.config %}
        {% set route = global.context.route() %}

        {% set type = global.blueprint_type ? global.blueprint_type : global.admin.location ? global.admin.location : 'config' %}

        {% set blueprint_name = global.blueprints.getFilename %}
        {% set real_path = path %}

        {% if type == 'pages' %}
            {% set blueprint_name = type ~ '/' ~ blueprint_name %}
            {% set real_path = (value.thumb ?? global.context.media[path].relativePath ?? global.form.getPagePathFromToken(path) ?? global.admin.getPagePathFromToken(path))|ltrim('/') %}
        {% endif %}
        {% set blueprint = blueprint_name|base64_encode %}


        {% set remove = global.file_task_remove ? global.file_url_remove : uri.addNonce(
            global.file_url_remove ~
            '/media.json' ~
            '/task' ~ config.system.param_sep ~ 'removeFileFromBlueprint' ~
            '/proute' ~ config.system.param_sep ~ (route|base64_encode) ~
            '/blueprint' ~ config.system.param_sep ~ blueprint ~
            '/type' ~ config.system.param_sep ~ type ~
            '/field' ~ config.system.param_sep ~ files.name ~
            '/path' ~ config.system.param_sep ~ (value.path|base64_encode), 'admin-form', 'admin-nonce') %}

        {% set file = value|merge({remove: remove, path: value.thumb_url ?? (uri.rootUrl == '/' ? '/' : uri.rootUrl ~ '/' ~ real_path) }) %}
        <div class="hidden" data-file="{{ file|json_encode|e('html_attr') }}"></div>
    {% endif %}
{% endmacro %}

{% import _self as macro %}

{% set defaults = config.plugins.form %}
{% set files = defaults.files|merge(field|default([])) %}
{% set limit = not field.multiple ? 1 : files.limit %}

{% block input %}
    {% set page_can_upload = exists or (type == 'page' and not exists and not (field.destination starts with '@self' or field.destination starts with 'self@')) %}
    {% if form or (type is not defined or page_can_upload) %}

    {% block prepend %}{% endblock %}
    {% set settings = {name: field.name, paramName: (scope ~ field.name)|fieldName ~ (files.multiple ? '[]' : ''), limit: limit, filesize: form_max_filesize, accept: files.accept, resolution: files.resolution, resizeWidth: files.resizeWidth, resizeHeight: files.resizeHeight, resizeQuality: files.resizeQuality } %}
    {% set dropzoneSettings = field.dropzone %}
    {% if form.getMediaTaskRoute() %}
        {% set file_url_add = base_url_relative ~ form.getMediaTaskRoute({}, 'json') %}
        {% set file_task_add = {task: 'media.upload', name: field.name, '__form-name__': form.name, '__unique_form_id__': form.uniqueid} %}

        {% set file_url_remove = base_url_relative ~ form.getMediaTaskRoute({}, 'json') %}
        {% set file_task_remove = {task: 'media.delete', name: field.name, '__form-name__': form.name, '__unique_form_id__': form.uniqueid} %}
    {% else %}
        {% set file_url_remove = file_url_remove ?: base_url_relative %}
    {% endif %}

    <div class="{{ form_field_wrapper_classes ?: 'form-input-wrapper' }} {{ field.classes }} dropzone files-upload {% if field.fancy is not same as(false) %}form-input-file{% endif %} {{ field.size }}"
         data-grav-file-settings="{{ settings|json_encode|e('html_attr') }}"
         data-dropzone-options="{{ dropzoneSettings|json_encode|e('html_attr') }}"
         {% if file_task_add and file_task_remove %}
             data-file-post-add="{{ file_task_add|json_encode|e('html_attr') }}"
             data-file-post-remove="{{ file_task_remove|json_encode|e('html_attr') }}"
             data-file-url-add="{{ file_url_add }}"
             data-file-url-remove="{{ file_url_remove }}"
         {% else %}
             {% if file_url_add %}data-file-url-add="{{ file_url_add }}"{% endif %}
             {% if file_url_remove %}data-file-url-remove="{{ file_url_remove }}"{% endif %}
         {% endif %}
    >

    {% block file_extras %}{% endblock %}
    <input
            {# required attribute structures #}
            {% block input_attributes %}
                type="file"
                {% if files.multiple %}multiple="multiple"{% endif %}
                {% if files.accept %}accept="{{ files.accept|join(',') }}"{% endif %}
                {% if field.disabled or isDisabledToggleable %}disabled="disabled"{% endif %}
                {% if field.random_name %}random="true"{% endif %}
                {% if required %}required="required"{% endif %}
                {{ parent() }}
            {% endblock %}
    />

    {% for path, file in value %}
        {{ macro.preview(path, file, _context) }}
    {% endfor %}
    {% include 'forms/fields/hidden/hidden.html.twig' with {field: {name: '_json.' ~ field.name}, value: (value ?? [])|json_encode} %}
    </div>

    {% else %}
        <span class="note">{{ "PLUGIN_ADMIN.CANNOT_ADD_FILES_PAGE_NOT_SAVED"|t|raw }}</span>
    {% endif %}
{% endblock %}
