// noinspection JSUnresolvedVariable
const {$, doAfterLoad} = window.fwdekker;
// noinspection JSUnresolvedVariable
const {clearFormValidity, showInputInvalid} = window.fwdekker.validation;


function toUppercaseAt(string, index) {
    return string.slice(0, index) + string.charAt(index).toUpperCase() + string.slice(index + 1);
}


doAfterLoad(() => {
    const debreviateForm = $("#debreviate-form");
    const abbreviationInput = $("#abbreviation");
    const abbreviationError = $("#abbreviation-error");
    const debreviationOutput = $("#debreviations");


    const showError = (message) => {
        if (message === undefined) {
            abbreviationError.innerText = "";
            debreviationOutput.classList.remove("hidden");
        } else {
            abbreviationError.innerText = message;
            debreviationOutput.classList.add("hidden");
        }
    };

    const debreviate = () => {
        clearFormValidity(debreviateForm);
        const abbreviation = abbreviationInput.value.trim();
        if (abbreviation === "") {
            showInputInvalid(abbreviationInput, "Abbreviation should be non-empty.");
            return;
        }

        const regex = new RegExp(abbreviation.split("").join(".*"));

        fetch("words.txt")
            .then(it => it.text())
            .then(text => text.split("\n").filter(it => !it.startsWith("#")).map(it => it.toLowerCase()))
            .then(words => words.filter(it => regex.test(it)))
            .then(matches =>
                matches.map(match =>
                    abbreviation
                        .split("")
                        .reduce(
                            (acc, letter) => {
                                const letterIndex = acc[0].indexOf(letter, acc[1]);
                                return [toUppercaseAt(acc[0], letterIndex), letterIndex];
                            },
                            [match, 0]
                        )[0]
                )
            )
            .then(matches => {
                if (matches.length === 0) {
                    showError("No debreviations found.");
                    return;
                }

                debreviationOutput.value = matches.join("\n");
                showError();
            });
    };

    debreviateForm.addEventListener("submit", event => {
        event.preventDefault();
        debreviate();
    });


    // Show page to user
    $("main").classList.remove("hidden");
    $("[autofocus]").focus();
});
