{% extends "wagtailadmin/generic/form.html" %}
{% load wagtailimages_tags wagtailadmin_tags i18n %}
{% block titletag %}{% trans "Add an image" %}{% endblock %}

{% block extra_js %}
    {{ block.super }}

    <script>
        $(function() {
            $('#id_file').on(
                'change',
                function() {
                    var $titleField = $('#id_title');

                    // do not override a title that already exists (from manual editing or previous upload)
                    if ($titleField.val()) return;

                    // file widget value example: `C:\fakepath\image.jpg` - convert to just the filename part
                    var filename = $(this).val().split('\\').slice(-1)[0];
                    var data = { title: filename.replace(/\.[^.]+$/, '') };
                    var maxTitleLength = parseInt($titleField.attr('maxLength') || '0', 10) || null;

                    // allow an event handler to customise data or call event.preventDefault to stop any title pre-filling
                    var form = $(this).closest('form').get(0);
                    var event = form.dispatchEvent(new CustomEvent(
                        'wagtail:images-upload',
                        { bubbles: true, cancelable: true, detail: { data: data, filename: filename, maxTitleLength: maxTitleLength } }
                    ));

                    if (!event) return; // do not set a title if event.preventDefault(); is called by handler

                    $titleField.val(data.title);
                }
            );
        });
    </script>
{% endblock %}

{% block actions %}
    <button
        type="submit"
        class="button button-longrunning"
        data-controller="w-progress"
        data-action="w-progress#activate"
        data-w-progress-active-value="{% trans 'Uploading…' %}"
    >
        {% icon name="spinner" %}
        <em data-w-progress-target="label">{% trans 'Upload' %}</em>
    </button>
{% endblock %}
