import axios from 'axios';

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

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

  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 validateMerchant(e) {
    e.preventDefault();

    if (request) {
      return;
    }

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

    request = true;
    axiosApi({
      method: 'get',
      url: validateMerchantUrl,
      params: { cielo_api_numero: credentialId.value, cielo_api_chave: 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', validateMerchant);
});
