// noinspection JSUnresolvedVariable
const {$, doAfterLoad, footer, header, nav} = window.fwdekker;


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


doAfterLoad(() => {
    $("#nav").appendChild(nav("/Tools/Debreviator/"));
    $("#header").appendChild(header({
        title: "Debreviator",
        description: "Creates meaning by undoing your abbreviation"
    }));
    $("#footer").appendChild(footer({
        vcsURL: "https://git.fwdekker.com/FWDekker/debreviator/",
        version: "v%%VERSION_NUMBER%%"
    }));
    $("main").classList.remove("hidden");
    $("[autofocus]").focus();
});

doAfterLoad(() => {
    const debreviate = () => {
        const abbreviation = $("#abbreviation").value.trim();
        if (abbreviation === "") 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 => $("#debreviations").value = matches.join("\n"));
    };

    $("#debreviate").addEventListener("click", debreviate);
    $("#abbreviation").addEventListener("keypress", event => {
        if (event.key === "Enter") {
            debreviate();
            event.preventDefault();
        }
    });
});
