import {urlSearchParams} from "../../../helpers";
import {handleResponse} from "../../helpers/rest";

/**
 * Get configs
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {object} params Query params
 * @return {Promise<any>}
 * @constructor
 */
export const GetConfigs = (restUrl, restNonce, params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${restUrl}configs${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}

/**
 * Get config
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {number} id Config id
 * @param {object} params Query params
 * @return {Promise<any>}
 * @constructor
 */
export const GetConfig = (restUrl, restNonce, id, params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${restUrl}configs/${id}${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}

/**
 * Create config
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {object} requestData Config data to create
 * @return {Promise<any>}
 * @constructor
 */
export const CreateConfig = (restUrl, restNonce, requestData) => {
    return fetch(`${restUrl}configs`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        },
        body: JSON.stringify(requestData)
    }).then(handleResponse);
}

/**
 * Update config
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {string} id Config ID
 * @param {object} requestData Config data to update
 * @return {Promise<any>}
 * @constructor
 */
export const UpdateConfig = (restUrl, restNonce, id, requestData) => {
    return fetch(`${restUrl}configs/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        },
        body: JSON.stringify(requestData)
    }).then(handleResponse);
}

/**
 * Delete config
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {string} id Config ID
 * @return {Promise<any>}
 * @constructor
 */
export const DeleteConfig = (restUrl, restNonce, id) => {
    return fetch(`${restUrl}configs/${id}`, {
        method: 'DELETE',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}