/*global ks_global*/

import jQuery from "jquery";

/**
 * Returns the json object from the stored graph as promise.
 *
 * @param {String} spaceId Identification of graph to load.
 *
 * @returns Promise returning graph object.
 */
export function loadGraphJson(spaceId) {
    let payload = {
        action: "get_space",
        space: spaceId,
    };

    return jQuery
        .ajax({
            type: "POST",
            url: ks_global.ajax_url,
            data: payload,
        })
        .then((data) => JSON.parse(data));
}

/**
 * Takes the graph json object and stores it in the backend.
 *
 * @param {String} spaceId Identification of graph to save.
 * @param {object} json Graph object
 *
 * @returns Promise returning state of query.
 */
export function saveGraphJson(spaceId, json) {
    let payload = {
        action: "update_space",
        graph: JSON.stringify(json),
        space: spaceId,
    };

    return jQuery.ajax({
        type: "POST",
        url: ks_global.ajax_url,
        data: payload,
    });
}

/**
 * Retrieves a list of all available spaces to choose from.
 *
 * @returns A promise containing an array containing all available space ids.
 */
export function listAllSpaces() {
    let payload = {
        action: "list_spaces",
    };

    return jQuery
        .ajax({
            type: "POST",
            url: ks_global.ajax_url,
            data: payload,
        })
        .then((data) => JSON.parse(data)["spaces"]);
}