
// Shorthand function for making an ajax request
// - sets the csrf token header
// - handles settings for sending data
async function ajaxRequest(url, method, data) {
    const options = {
        url: url,
        method: method,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("X-CSRFToken", CSRF_MiddlewareToken);
        }
    }
    
    if (data) {
        options.data = data;
        options.processData = false;
        options.contentType = false;
    }

    try {
        const response = await $.ajax(options);
        return response
    }
    catch (error) {
        return error
    }
}


// Create a querystring from any given filters and sort options.
function makeQuerystring(filters, sort) {
    let querystring = "?";
    for (key in filters) {
        querystring += `${key}=${filters[key]}&`;
    }

    return sort ? querystring += `ordering=${sort}` : querystring;
}


// Convert any given object to a new FormData instance, and return it.
function objectToFormData(object) {
    let formData = new FormData();

    Object.keys(object).forEach(key => {
        let value = object[key];

        if (value === null || value === undefined) {
            return;
        }

        if (Array.isArray(value)) {
            value.forEach(part => {
                formData.append(key, part);
            })
        }
        else if (typeof value === "object" && !(value instanceof File)) {
            Object.keys(value).forEach(nestedKey => {
                formData.append(`${key}[${nestedKey}]`, value[nestedKey]);
            });
        }
        else {
            formData.append(key, value);
        }
    });

    return formData;
}
