const input = document.querySelector('#otp-setup-form input[name="otp_code"]');
const submit_btn = document.querySelector('#otp-setup-form button[name="submit"]');
const error_wrapper = document.querySelector('#otp-setup-form .error-wrapper');

input.addEventListener('keyup', (e) => {
    var code = e.currentTarget.value;
    var otp_secret = document.querySelector('input[name="otp_secret"]').value;

    if (code.length === 6) {
        var formData = new FormData();
        formData.append("otp_code", code);
        formData.append("otp_secret", otp_secret);
        request('/account/otp-verify', formData, function (data) {
            try {
                data = JSON.parse(data);
                if ((data instanceof Object)) {
                    if (data['status']) {
                        submit_btn.disabled = false;
                        error_wrapper.innerHTML = "";
                    } else {
                        error_wrapper.innerHTML = "<div class=\"text-danger mb-3\">" + data['message'] + "</div>";
                    }
                }
            } catch (e) {
                console.log("An unexpected error occurred");
            }
        });

    } else {
        submit_btn.disabled = true;
    }
});