import ModalMidias from "../classes/ModalMidias.js";
import Repeat from "../classes/Repeat.js";

jQuery(function ($) {

  /* Função para atribuir imagem a um image field */
  function setImageField(attachment, element) {
    const field = $(element);
    field.children('input').val(attachment.id);
    field.find('.o2-image-field-editor-image').attr('src', attachment.url);
    field.find('.o2-image-field-details-title').html(attachment.title).trigger('change');
    field.find('.o2-image-field-details-filename').html(attachment.filename);
    field.find('.o2-image-field-details-type').html(attachment.mime);
    field.find('.o2-image-field-details-dimension').html(attachment.width + 'x' + attachment.height);
    field.find('.o2-image-field-details-filesize').html(attachment.filesizeHumanReadable);
    field.children('.o2-image-field-unselected').addClass('d-none');
    field.children('.o2-image-field-selected').removeClass('d-none');
  }

  $(document).on('click', '.o2-image-field-add', function () {
    const field = $(this).closest('.o2-image-field');

    var repeatEl = field.closest('.o2-repeat');
    var multiple = repeatEl.length > 0;

    const imageModal = new ModalMidias((attachment) => {
      if (multiple) {
        var repeat = repeatEl.data('repeat');
        var name = field.find('[type="hidden"]').attr('name');
        var fieldName = repeat.getName(name);
        var index = field.closest('.o2-repeat-item').prevAll().length;

        var nameFields = [name];
        for (var i = 1; i < attachment.length; i++) nameFields.push(fieldName.replace('{{INDEX}}', index + i));

        /* Adicionando itens e atributindo imagens a eles */
        nameFields.forEach((name, i) => {
          var element = $(`[name="${name}"]`).closest('.o2-image-field');
          if (!element.length) {
            repeat.addItem(index + i);
            repeat.update();
            var element = $(`[name="${name}"]`).closest('.o2-image-field');
          }
          setImageField(attachment[i], element);
        });

      } else {
        setImageField(attachment, field);
      }
    }, multiple);
    imageModal.openModal();
  });

  /* Editar imagem field */
  $(document).on('click', '.o2-image-field-edit', function () {
    $(this).closest('.o2-image-field').find('.o2-image-field-add').trigger('click');
  });

  /* Remover Imagem field */
  $(document).on('click', '.o2-image-field-remove', function () {
    const field = $(this).closest('.o2-image-field');
    field.children('input').val('');
    field.find('.o2-image-field-details-title').text("").trigger('change');
    field.children('.o2-image-field-unselected').removeClass('d-none');
    field.children('.o2-image-field-selected').addClass('d-none');
  });

});