{% load static i18n %}

{% block GALLERY_WIDGET_CSS_EXTRA %}
{% endblock %}


{% block GALLERY_WIDGET_HTML %}

  <div class="gallery-widget" id="id-{{ name }}-gallery-widget">

    {{ input_string }}

    {% if not uploader_disabled and upload_url %}
      {% block GALLERY_WIDGET_UPLOAD_FORM_BUTTON_BAR %}
        <div class="row fileupload-buttonbar">

          {# The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload #}

          <div class="col-lg-7">

            {# The fileinput-button span is used to style the file input field as button #}

            {% block GALLERY_WIDGET_BUTTON_BAR_ADD %}
              <span class="btn btn-success fileinput-button{% if uploader_disabled %} hidden{% endif %}">
                <i class="si-solid si-plus"></i>
                <span>{% trans "Add files..." %}</span>

                {% block GALLERY_WIDGET_BUTTON_BAR_ADD_FILE_INPUT %}
                  {% comment %}
                    GALLERY_WIDGET_BUTTON_BAR_ADD_FILE_INPUT and GALLERY_WIDGET_FILE_INPUT
                    control the same block.

                    FILE_INPUT is the original and shorter block name that has
                    been kept to function as a convenient alias as well as to
                    allow backward-compatibility with dependent projects.

                    Note: Only one should be overridden in the inheriting templates.
                  {% endcomment %}

                  {% block GALLERY_WIDGET_FILE_INPUT %}
                    {# The file input for the upload form. #}
                    <input
                      type="file" class="gallery-widget-image-input" id="{{ name }}-files"
                      {% if multiple %}multiple{% endif %}

                      {% if accepted_mime_types %}accept='{{ accepted_mime_types|join:"," }}'{% endif %}
                      data-action="{{ upload_url }}"
                      {% if uploader_disabled %}disabled{% endif %}
                    >
                  {% endblock %}
                {% endblock %}
              </span>

              {% block GALLERY_WIDGET_BUTTON_BAR_ADD_EXTRA %}
              {% endblock %}

            {% endblock %}

            {% block GALLERY_WIDGET_BUTTON_BAR_CONTROL %}
              <button type="submit" class="btn btn-primary start {% if uploader_disabled %} hidden disabled {% endif %}"
                      style="display: none;">
                <i class="si-solid si-upload"></i>
                <span>{% trans "Start upload" %}</span>
              </button>
              <button type="reset" class="btn btn-warning cancel {% if uploader_disabled %} hidden disabled {% endif %}"
                      style="display: none;">
                <i class="si si-cancel"></i>
                <span>{% trans "Cancel upload" %}</span>
              </button>
              <button type="button" class="btn btn-danger delete {% if uploader_disabled %} hidden disabled {% endif %}"
                      style="display: none;">
                <i class="si-regular si-trash-can"></i>
                <span>{% trans "Delete" %}</span>
              </button>
              <input type="checkbox" class="toggle {% if uploader_disabled %} hidden disabled {% endif %}"
                     style="display: none;">
            {% endblock %}

            {% block GALLERY_WIDGET_BUTTON_BAR_EXTRA %}
            {% endblock %}

          </div>

          {% block GALLERY_WIDGET_PROGRESS_BAR %}
            {# The global progress information #}

            <div class="col-lg-5 fileupload-progress fade">

              {# The global progress bar#}
              <div
                class="progress progress-striped active"
                role="progressbar"
                aria-valuemin="0" aria-valuemax="100"
              >
                <div class="progress-bar progress-bar-success" style="width:0;">
                </div>
              </div>

              {# The extended global progress information #}
              <div class="progress-extended">&nbsp;</div>
            </div>
          {% endblock %}

        </div>
      {% endblock %}

      {# The loading indicator is shown during file processing #}

      {% block GALLERY_WIDGET_LINDICATOR %}
        <div class="fileupload-loading"></div>
        <br>
      {% endblock %}

    {% endif %}

    {% block GALLERY_WIDGET_LISTING %}
      {# The table listing the files available for upload/download #}
      <table role="presentation" class="table table-striped">
        <tbody class="files"></tbody>
      </table>
    {% endblock %}

    {% block GALLERY_WIDGET_EXTRA %}
    {% endblock %}


    {% block GALLERY_WIDGET_MODAL_GALLERY %}
      {% comment %}
        Note: data-filter=":even" is important because we have 2 link for each image (in download template),
        so we just pick one (the even one, maybe "odd" also works) to use in gallery ui, or else each image
        will show twice in the gallery.
      {% endcomment %}
      <div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
        <div class="slides"></div>
        <h3 class="title"></h3>
        <a class="prev"></a>
        <a class="next"></a>
        <a class="close"></a>
        <a class="play-pause"></a>
        <ol class="indicator"></ol>
      </div>
    {% endblock %}


    {% block GALLERY_WIDGET_TMPL_TEMPLATES %}
      {# The template to display files available for upload #}

      {% block GALLERY_WIDGET_TMPL_UPLOAD_TEMPLATE %}
        <script id="template-upload" type="text/x-tmpl">
          {% include upload_template %}
        </script>
      {% endblock %}

      {% block GALLERY_WIDGET_TMPL_DOWNLOAD_TEMPLATE %}
        {# The template to display files available for download #}

        <script id="template-download" type="text/x-tmpl">
          {% include download_template %}
        </script>
      {% endblock %}

    {% endblock %}


    {% block GALLERY_WIDGET_EDIT_MODAL %}
      {# editModal #}
      <div class="modal fade edit-modal" role="dialog" aria-labelledby="modalLabel"
         tabindex="-1">
      <div class="modal-dialog modal-lg modal-sm" role="document">
        <div class="modal-content">
          <div class="modal-header visible-lg">
            {% if bootstrap_version == 3 %}
              <button type="button" class="close" data-dismiss="modal"
                      aria-label="Close"><span aria-hidden="true">&times;</span>
              </button>
            {% endif %}
            <h4 class="modal-title" id="modalLabel">{% trans "Edit image" %}</h4>
            {% if bootstrap_version > 3 %}
              <button type="button" class="{% if bootstrap_version == 4 %}close{% else %}btn-close{% endif %}"
                      {% if bootstrap_version == 4 %}data-dismiss{% else %}data-bs-dismiss{% endif %}="modal"
                      aria-label="Close"><span aria-hidden="true">{% if bootstrap_version == 4 %}
                &times;{% endif %}</span>
              </button>
            {% endif %}
          </div>
          <div class="modal-body">
            <div class="img-container">
              <img class="img-responsive modal-image" src="" alt="" data-ajax-url="">
            </div>
          </div>
          <div class="modal-footer">
            <div class="cropper-message" style="padding: 0; margin-bottom: 0; margin-left: 0; float: left;"></div>
            <div>
              <div class="btn-group cropper-btns">
                <div class="btn-group cropper-rotate-btns">
                  <button type="button" class="btn btn-primary" disabled
                          data-method="rotate" data-option="-90">
                    <i class="si si-format-rotate-90"></i>
                    <span>-90</span>
                  </button>
                  <button type="button" class="btn btn-primary" disabled
                          data-method="rotate" data-option=90>
                    <i class="si si-format-rotate-90 si-flip-horizontal"></i>
                    <span>90</span>
                  </button>

                </div>
                <div class="btn-group cropper-status-btns">
                  <button type="button"
                          class="btn btn-success" disabled
                          data-method="commit">
                    <i class="si-solid si-check"></i>
                    <span>{% trans "Submit" %}</span></button>
                  <button type="button"
                          class="btn btn-warning" disabled
                          data-method="reset">
                    <i class="si si-sync"></i>
                    <span>{% trans "Reset" %}</span></button>
                </div>
              </div>
              <div class="btn-group cropper-btns">
                <button type="button" class="btn btn-danger"
                        {% if bootstrap_version < 5 %}data-dismiss{% else %}data-bs-dismiss{% endif %}="modal">
                  <i class="si-solid si-xmark"></i>
                  <span>{% trans "Close" %}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    {% endblock %}

  </div>

{% endblock %}

{% block GALLERY_WIDGET_JS %}
  <script type="text/javascript">
    (function (factory) {
      if (typeof define === 'function' && define.amd)
        define(['jquery'], factory)
      else if (typeof module === 'object' && module.exports)
        module.exports = factory(require('jquery'))
      else
        factory(jQuery)
    }(function ($) {

      function get_cookie(name) {
        let cookieValue;
        if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
            const cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
            }
          }
        }
        return cookieValue;
      }

      {% if prompt_alert_on_window_reload_if_changed %}
        let input_changed = false;

        function on_input_change(evt) {
          input_changed = true;
        }

        $(window).on('beforeunload', function (evt) {
          if (input_changed)
            return "{% trans 'You have unsaved changes on this page.' %}";
        });
        {% block GALLERY_WIDGET_FORM_SUBMIT_BUTTON %}
          // We can't simply set "disabled" on the submitting button here.
          // Otherwise the browser will simply remove that button from the POST
          // data.
          function before_submit(evt) {
            input_changed = false;

            $(".gallery-widget-submit-button").each(
              function () {
                const clone = $(this).clone();
                $(clone).attr("disabled", "1");
                $(this).after(clone);
                $(this).hide();
              });
          }
        {% endblock %}

      {% endif %}

      $(function () {
        const $fileupload = $("#id-{{ name }}-gallery-widget"),
          fileInput = $('#{{ name }}-files'),
          uploadURL = fileInput.data('action'),
          sortableOptions = {
            {{ jquery_fileupload_ui_sortable_options|safe }}
          };

        $fileupload.fileupload({
          singleFileUploads: true,
          url: uploadURL,
          type: 'POST',
          hiddenFileInput: 'input#id_{{ name }}',
          messages: {
            maxFileSize: '{% trans "File is too big" %}',
            minFileSize: '{% trans "File is too small" %}',
            acceptFileTypes: '{% trans "Filetype not allowed" %}',
            {% if maxNumberOfFiles %}
              maxNumberOfFiles: "{% blocktrans trimmed %} Number of images exceeded, only {{ maxNumberOfFiles }}
                allowed{% endblocktrans %}",
            {% endif %}
            uploadedBytes: '{% trans "Uploaded bytes exceed file size" %}',
            emptyResult: '{% trans "Empty file upload result" %}'
          },
          {{ jquery_fileupload_ui_options|safe }}

          sortableOptions: sortableOptions,

          change: function (e, data) {
            if (typeof on_input_change !== 'undefined') on_input_change();
          },
          inputChanged: function (e, data) {
            if (typeof on_input_change !== 'undefined') on_input_change();
          },

          csrfCookieFunction: function () {
            return get_cookie('{{ csrfCookieName }}')
          },
        });

        {% if pks and fetch_url %}
          {# Do not remove the comment below, we are using it for tests. #}
          // fetching existing images
          $fileupload.find(".hiddeninput").addClass("initializing");
          $.ajax({
            url: "{{ fetch_url }}",
            dataType: 'json',
            data: {"pks": encodeURIComponent(JSON.stringify({{pks}}))},
            context: $fileupload[0]
          }).always(function () {
            $(this).removeClass('fileupload-processing');
            $(".fileupload-loading").remove();
          }).done(function (result) {
            $(this).fileupload('option', 'done')
              .call(this, $.Event('done'), {result: result});
          });

        {% endif %}

        // disable change alert when submit form.
        if (typeof before_submit !== 'undefined') {
          $fileupload.closest("form").on("submit", before_submit);
        }
      });

      {% if not uploader_disabled and upload_url %}

        // Remove 'multiple' attribute from file input when uploading from
        // wechat built-in browser

        $(document).ready(function () {
          const isWeixinBrowser = (/micromessenger/i).test(navigator.userAgent);
          if (isWeixinBrowser)
            $('.gallery-widget-image-input')
              .removeAttr('multiple')
              .attr("accept", "image/*");
        })
      {% endif %}

    }));
  </script>
{% endblock %}

{% block GALLERY_WIDGET_JS_EXTRA %}
{% endblock %}
