jQuery(document).ready(function ($) {

    $("#token_field").on("input", () => {
        get_workspaces()
    })

    get_workspaces = () => {
        const data = {
            'action': "get_workspaces",
            'token': $("#token_field").val()
        };

        doAjaxQuery(data, (response) => {
            const wsField = $("#ws_select_field")
            wsField.prop("disabled", false).removeClass("blinking").empty()

            if (response.success) {
                for (const ws of response.data.data) {
                    let name = ws.term
                    let id = ws._id.$oid
                    let saved_ws_id = Data.saved_ws_id

                    addOption(wsField, name, id, id === saved_ws_id)
                }
            } else {
                addOption(wsField, "Пространства не найдены")
                wsField.prop("disabled", true)
            }
        });
    }

    addOption = (selectField, text, val="", isSelected=false) => {
        const $option = $("<option></option>")
            .text(text)
            .val(val)
            .prop("selected", isSelected);

        selectField.append($option);
    }

    get_workspaces()
});