$(document).ready(function() {
  var token = $('body').data('token');

  function filter() {
    url = 'index.php?route=specific/4861/module/material&token=' + token;
    var filter_name = $("input[name='filter_name']").attr('value');
    if (filter_name) {
      url += '&filter_name=' + encodeURIComponent(filter_name);
    }
    location = url;
  }

  $('.js-btn-filter').on('click', function(event) {
    event.preventDefault();
    filter();
  });

  $("input[name='filter_name']").on('keyup', function(event) {
    if (event.keyCode == 13) {
      filter();
    }
  });

  const openFileManager = document.querySelectorAll('.js-open-file-manager');

  for (const iterator of openFileManager) {
    iterator.addEventListener('click', () => {
      const container = iterator.closest('.js-file-container');
      handleFileManager(container);
    });
  }

  function handleFileManager(container) {
    const archive = container.classList.contains('js-archive');
    window.dispatchEvent(
      new CustomEvent('vue-file-manager', {
        detail: {
          callbackFunction: file => {
            container.querySelector('input').value = 'data/' + file.file;
            container.querySelector('img').src =
              archive && file.thumbnail == '' ? '../image/no_image.jpg' : file.thumbnail;

            if (archive) {
              container.querySelector('.js-archive-name').textContent = file.filename;
            }
          },
          options: {
            maxWidth: !archive ? 1920 : '',
            maxHeight: !archive ? 1080 : '',
            minWidth: !archive ? 16 : '',
            minHeight: !archive ? 16 : '',
            showFolderIcons: !archive ? true : false,
          },
        },
      })
    );
  }

  const removeButtons = document.querySelectorAll('.js-btn-clear-image');

  for (const item of removeButtons) {
    item.addEventListener('click', () => {
      const container = item.closest('.js-file-container');
      removeImage(container);
    });
  }

  function removeImage(container) {
    container.querySelector('input').value = '';
    container.querySelector('img').src = '../image/no_image.jpg';
  }
});
