import documentReady from '@assets/js/documentReady';

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

  const pagseguro_email = document.querySelector('input[name="pagseguro_email"]');
  const pagseguro_token = document.querySelector('input[name="pagseguro_token"]');

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

  handleAuthenticateButton();

  pagseguro_email.addEventListener('change', handleAuthenticateButton);
  pagseguro_token.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: { pagseguro_email: pagseguro_email.value, pagseguro_token: pagseguro_token.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);
});
