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="yapay_token"]');

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

  handleAuthenticateButton();

  credentialId.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: { yapay_token: credentialId.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);
});
