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

  $('.js-notification-delete').on('click', function() {
    $('.warning, .success').remove();

    var $this = $(this),
      data = {};
    data['notification_id'] = $this.data('notification-id');

    $.ajax({
      url: 'index.php?route=payment/wirecard/deleteNotification&token=' + token,
      type: 'post',
      data: data,
      dataType: 'json',
      beforeSend: function() {
        $this.find('i').remove();
        $this.append(
          '<img class="js-loading-notification" src="../assets/img/loading-black.svg" alt="Carregando..." />'
        );
        $this.attr('disabled', true);
        $this.addClass('hidden');
      },
      complete: function() {
        $this.removeClass('hidden');
        $this.attr('disabled', false);
        $this.find('.js-loading-notification').remove();
      },
      success: function(json) {
        if (json['success']) {
          $this.closest('.js-content-notification').fadeOut('slow');
          location.reload();
        }

        if (json['error']) {
          $('.js-header-notifications').append('<div class="warning full-width">' + json['error'] + '</div>');
        }
      },
    });
  });

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

  for (const iterator of openFileManager) {
    iterator.addEventListener('click', () => {
      handleFileManager();
    });
  }

  function handleFileManager() {
    window.dispatchEvent(
      new CustomEvent('vue-file-manager', {
        detail: {
          callbackFunction: file => {
            document.querySelector('#logo-boleto').value = 'data/' + file.file;
            document.querySelector('#thumb-logo-boleto').src = file.thumbnail;
          },
          options: {
            maxWidth: 80,
            maxHeight: 25,
            minWidth: 16,
            minHeight: 16,
          },
        },
      })
    );
  }

  document.querySelector('.js-btn-clear-image').addEventListener('click', removeImage);

  function removeImage() {
    document.querySelector('#logo-boleto').value = '';
    document.querySelector('#thumb-logo-boleto').src = '../image/no_image.jpg';
  }

  // Validate credentials
  const buttonTestConnection = document.querySelector('.js-validate-credentials');
  const validateCredentialsUrl = buttonTestConnection.dataset.url;
  let request = false;

  const credentialId = document.querySelector('input[name="wirecard_token"]');
  const credentialKey = document.querySelector('input[name="wirecard_key_access"]');

  function handleAuthenticateButton() {
    if (!credentialId.value || !credentialKey.value) {
      buttonTestConnection.setAttribute('disabled', true);
    } else {
      buttonTestConnection.removeAttribute('disabled', true);
    }
  }

  handleAuthenticateButton();

  credentialId.addEventListener('change', handleAuthenticateButton);
  credentialKey.addEventListener('change', handleAuthenticateButton);

  function validateCredentials(e) {
    e.preventDefault();

    if (request) {
      return;
    }

    this.classList.add('btn-loading');
    this.disabled = true;

    request = true;
    window
      .axiosApi({
        method: 'get',
        url: validateCredentialsUrl,
        params: { wirecard_token: credentialId.value, wirecard_key_access: credentialKey.value },
      })
      .then(({ data }) => {
        notificationMsg(data.message, data.type);
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {
        this.classList.remove('btn-loading');
        this.disabled = false;
        request = false;
      });
  }

  buttonTestConnection.addEventListener('click', validateCredentials);
});
