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

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

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

/**
 * Upload file
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {binary[]} files Files to upload
 * @return {Promise<any>}
 * @constructor
 */
export const UploadFiles = (restUrl, restNonce, files) => {
    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        formData.append('file' + (i + 1), files[i]);
    }

    return fetch(`${restUrl}files/upload/batch`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        },
        body: formData
    }).then(handleResponse);
}

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

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

/**
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {string} uuid File UUID
 * @return {Promise<Response>}
 * @constructor
 */
export const DeleteFile = (restUrl, restNonce, uuid) => {
    return fetch(`${restUrl}files/${uuid}`, {
        method: 'DELETE',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}

/**
 * Import files from WordPress Media Library
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {number[]} attachmentIds Array of WordPress attachment IDs
 * @return {Promise<any>}
 * @constructor
 */
export const ImportFromMedia = (restUrl, restNonce, attachmentIds) => {
    return fetch(`${restUrl}files/import/media`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-WP-Nonce': restNonce
        },
        body: JSON.stringify({
            attachment_ids: attachmentIds
        })
    }).then(handleResponse);
}
