
function validCredentialName() {
    let name = document.getElementById('credential_name');
    let msg = document.getElementById('name-feedback');

    if (name.value.length > 5) {
        name.classList.remove('is-invalid');
        name.classList.add('is-valid');
        msg.classList.add('d-none');
        return true;
    }

    name.classList.add('is-invalid');
    msg.classList.remove('d-none');
    return false;
}



up.compiler('#webauthn_register', function (element, params) {
    "use strict";

    const { startRegistration } = SimpleWebAuthnBrowser;
    const elemBegin = document.getElementById('btn_webauthn_begin');
    const elemSuccess = document.getElementById('btn_webauthn_success');
    const elemError = document.getElementById('btn_webauthn_error');

    // Start registration when the user clicks a button
    elemBegin.addEventListener('click', async (evt) => {

        if (!validCredentialName()) {
            evt.preventDefault();
            return;
        }

        // Reset success/error messages
        elemSuccess.innerHTML = '';
        elemError.innerHTML = '';

        // GET registration options from the endpoint that calls
        // @simplewebauthn/server -> generateRegistrationOptions()
        const optionsJSON = params.public_credential_creation_options;

        let attResp;
        try {
          // Pass the options to the authenticator and wait for a response
          attResp = await startRegistration({ optionsJSON });
        } catch (error) {
          // Some basic error handling
          if (error.name === 'InvalidStateError') {
            elemError.innerText = 'Error: Authenticator was probably already registered by user';
          } else {
            elemError.innerText = error;
          }

          throw error;
        }

        // POST the response to the endpoint that calls
        // @simplewebauthn/server -> verifyRegistrationResponse()
        let name = document.getElementById('credential_name');
        attResp.credential_name = name.value;
        const verificationResp = await fetch(params.verification_url, {
          method: 'POST',
          headers: {
              'X-CSRFToken': params.csrf_token,
              'Content-Type': 'application/json',
          },
          body:  JSON.stringify(attResp),
        });

        // Wait for the results of verification
        const verificationJSON = await verificationResp;

        // Show UI appropriate for the `verified` status
        if (verificationJSON.status === 201) {
            window.location.replace(params.verified_url);
        } else {
            console.log('Something went wrong!');
            location.reload();
        }
    });

});
