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

/**
 * Get jobs
 *
 * @param {object} params Query params (chatbot_uuid, sub_type, etc.)
 * @return {Promise<any>}
 */
export const GetJobs = (params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${LimbChatbot.rest.url}jobs${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
}

/**
 * Create job
 *
 * @param {object} requestData Job data to create
 * @return {Promise<any>}
 */
export const CreateJob = (requestData) => {
    return fetch(`${LimbChatbot.rest.url}jobs`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        },
        body: JSON.stringify(requestData)
    }).then(handleResponse);
}

/**
 * Get job (stats)
 *
 * @param {number} jobId Job ID
 * @return {Promise<any>}
 */
export const GetJob = (jobId) => {
    return fetch(`${LimbChatbot.rest.url}jobs/${jobId}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
}

/**
 * Continue/process job
 *
 * @param {number} jobId Job ID
 * @return {Promise<any>}
 */
export const ProcessJob = (jobId) => {
    return fetch(`${LimbChatbot.rest.url}jobs/${jobId}/process`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
}

/**
 * Resume job
 *
 * @param {number} jobId Job ID
 * @return {Promise<any>}
 */
export const ResumeJob = (jobId) => {
    return fetch(`${LimbChatbot.rest.url}jobs/${jobId}/resume`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
}

/**
 * Pause job
 *
 * @param {number} jobId Job ID
 * @return {Promise<any>}
 */
export const PauseJob = (jobId) => {
    return fetch(`${LimbChatbot.rest.url}jobs/${jobId}/pause`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
}

/**
 * Cancel job
 *
 * @param {number} jobId Job ID
 * @return {Promise<any>}
 */
export const CancelJob = (jobId) => {
    return fetch(`${LimbChatbot.rest.url}jobs/${jobId}/cancel`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
}
