/**
 * Checks if a string is valid (not null and not empty)
 * @param {string} str 
 * @returns true if valid, false otherwise
 */
function ValidString(str) {
    if (str) {
        if (str.length > 0) {
            return true;
        }
    }
    return false;
}

/**
 * Performs a POST request to the specified URL with the given data.
 * @param {string} url Service endpoint URL
 * @param {object} data Data to be sent in the request body
 * @param {function} onSuccess callback for successful response
 * @param {function} onError callback for error response
 */
function Post(url, data, onSuccess, onError) {
    fetch(url, {
        method: "POST",
        body: JSON.stringify(data)
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            let str = `POST request to ${url} failed. Status: ${response.statusText}`;
            throw new Error(str);
        }
    }).then(data => {
        if (onSuccess) {
            onSuccess(data);
        }
    }).catch(error => {
        if (ValidString(error.message)) {
            if (onError) {
                onError(error.message);
            } else {
                console.error(error.message);
            }
        } else console.log("An unknown error occurred during POST request.");

    });
}

/**
 * Performs a GET request to the specified URL.
 * @param {string} url Service endpoint URL
 * @param {function} onSuccess callback for successful response
 * @param {function} onError callback for error response
 */
function Get(url, onSuccess, onError) {
    fetch(url).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            let str = `GET request to ${url} failed. Status: ${response.statusText}`;
            throw new Error(str);
        }
    }).then(data => {
        if (onSuccess) {
            onSuccess(data);
        }
    }).catch(error => {
        if (ValidString(error.message)) {
            if (onError) {
                onError(error.message);
            } else {
                console.error(error.message);
            }
        }
        else console.log("An unknown error occurred during GET request.");
    });
}