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

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

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

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

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

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

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

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