import jQuery from "jquery";

Object.assign(window, { $: jQuery, jQuery });

import Cookies from "js-cookie";

require("select2/dist/js/i18n/cs");
import "select2/dist/js/select2.full";
import "select2/dist/css/select2.min.css";

$(window).ready(
    () => {
        const RV_MEMBERS = JSON.parse($("#rv-members")[0].textContent);

        $(".__vote-selection").select2({
            tags: true,
            tokenSeparators: [",", " "],
            // https://stackoverflow.com/a/28657702 - Thanks to Artur Filipiak!
            createTag: tag => {
                return {
                    id: tag.term,
                    text: tag.term,
                    isNew : true
                };
            }
        });

        $(".__vote-selection").on(
            "select2:selecting",
            event => {
                // Prevent empty tags.
                if (event.params.args.data.id == "") {
                    event.preventDefault();
                }
            }
        );

        $(".__vote-selection").on(
            "select2:select",
            event => {
                $("#count-votes").prop("disabled", false);

                // Keep user-defined ordering. This is imperative!
                // http://github.com/select2/select2/issues/3106 - Thanks to kevin-brown!
                const element = $(event.params.data.element);
                
                element.detach();
                $(this).append(element);
                $(this).trigger("change");
            }
        );

        $(".__vote-selection").on(
            "select2:unselect",
            event => {
                for (const selection of $(".__vote-selection")) {
                    if ($(selection).select2("data").length !== 0) {
                        return;
                    }
                }

                $("#count-votes").prop("disabled", true);
            }
        );

        $("#count-votes").on(
            "click",
            async (event) => {
                $(event.currentTarget).addClass("btn--loading").prop("disabled", true);

                let votes = {};

                for (const username of Object.keys(RV_MEMBERS)) {
                    const selectedOptions = $(`#${$.escapeSelector(username)}-selection`).select2("data");

                    if (selectedOptions.length === 0) {
                        continue;
                    }

                    votes[username] = [];

                    for (const option of selectedOptions) {
                        votes[username].push(option.id);
                    }
                }

                const urlParams = new URL(window.location).searchParams;
                const rvGid = urlParams.get("rv_gid");
                const seed = urlParams.get("seed");

                let response = await fetch(
                    VOTE_CALCULATION_ENDPOINT
                    + `?votes=${encodeURIComponent(JSON.stringify(votes))}`
                    + (
                        (rvGid !== null) ?
                        `&rv_gid=${encodeURIComponent(rvGid)}` : ""
                    )
                    + (
                        (seed !== null) ?
                        `&seed=${encodeURIComponent(seed)}` : ""
                    )
                );

                if (!response.ok) {
                    alert("Chyba při získávání výsledků hlasování.");
                    return;
                }

                $("#result").html(await response.text());

                $("#permalink,#download-log").show();
                $("#permalink").attr(
                    "href",
                    (
                        // Base URL
                        window.location.href.split('?')[0]
                        + `?votes=${encodeURIComponent(JSON.stringify(votes))}`
                        + `&rv_gid=${encodeURIComponent(Cookies.get("rv_gid"))}`
                        + `&seed=${encodeURIComponent(Cookies.get("seed"))}`
                    )
                );
                $("#download-log").attr(
                    "href",
                    (
                        "data:text/plain;charset=utf-8,"
                        + encodeURIComponent($("#md-steps").html())
                    )
                );

                $("#result")[0].scrollIntoView();
                $(event.currentTarget).removeClass("btn--loading").prop("disabled", false);
            }
        );
    }
)