document.addEventListener('DOMContentLoaded', function() {
  const buttonTestConnection = document.querySelector('.js-validate-credentials');
  const validateCredentialsUrl = buttonTestConnection.dataset.url;
  let request = false;

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

  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: { payu_apilogin: credentialId.value, payu_apikey: 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);
});
