/** This file centralize all HTTP requests used for the logbook */
import axios from 'axios';
import {
    getEventCountByInvestigationId as getEventCountByInvestigationIdURL,
    getEventsByInvestigationId as getEventsByInvestigationIdURL,
    getTagsByInvestigationId as getTagsByInvestigationIdURL,
    createEvent as createEventURL,
    updateEvent as updateEventURL
} from '../../api/icat/icatPlus.js';


/**
 * Request events associated to the given investigationId and selectionFilter
 * @param {integer} investigationId investigation identifier
 * @param {integer} limit total number of events requested
 * @param {integer} offset offset value of events from all events found by the DB (used for pagination)
 * @param {} onSuccess callback function trigered when the requests succedded.
 * @param {} onError callback function executed when an error occured during the request.
 * @param {Object} selectionFilter selection filter (DB syntax). Example: {"$and": [{"$or": [{"type": "annotation"},{"type": "notification"}]}]}
 * @param {String} sessionId session identifier
 * @param {Object} sortingFilter sorting filter (DB synthax). Example: {"createdAt": -1}
 */
export const getEventsByInvestigationId = (sessionId, investigationId, limit, offset, selectionFilter, sortingFilter, onSuccess, onError) => {
    if (investigationId && sessionId) {
        axios({
            method: 'post',
            url: getEventsByInvestigationIdURL(sessionId, investigationId),
            data: {
                find: selectionFilter,
                sort: sortingFilter,
                limit: limit,
                skip: offset
            }
        })
            .then(data => {
                onSuccess(data);
            })
            .catch((error) => {
                console.log('[ERROR] An error occured while retrieving the event list.');
                onError(error);
            });
    } else {
        onError('[ERROR] Missing query parameters in the request handled by getEventsByInvestigationId()');
    }
}

/**
* Request number of events associated to the given investigationId and a given selection filter. This informs the client about how many events for a given selection filter are available on 
* the server. THis information is not provided by getEventsByInvestigationId because the event list size is configured to a maximum event per download.
* @param {string} investigationId the investigation id
* @param {string} sessionId the session id
* @param {object} selectionFilter the selection filter
* @param {func} onSuccess the callback function executed when the request succeeds
* @param {func} onError the callback function executed when an error occured during the request.
*/
export const getEventCountByInvestigationId = (investigationId, sessionId, selectionFilter, onSuccess, onError) => {
    if (investigationId && sessionId) {
        axios({
            method: 'post',
            url: getEventCountByInvestigationIdURL(sessionId, investigationId),
            data: { find: selectionFilter }
        })
            .then(data => {
                onSuccess(data);
            })
            .catch((error) => {
                console.log('[ERROR] An error occured while retrieving the event count.');
                onError(error);
            });
    } else {
        onError('[ERROR] Missing query parameters in the request handled by getEventCountByInvestigationId()');
    }
}

/**
    * Create the event on ICAT+ server
    * @param {*} newEvent event object to be created
    * @param {String} sessionId session Id required for HTTP request authentication
    * @param {*} investigationId investigation Id to which the event will be added to.
    * @param {*} onSuccess callback function executed after the asymchronous event creation process succeeded.
    */
export const createEvent = (newEvent, sessionId, investigationId, onSuccess) => {
    axios({
        method: 'post',
        url: createEventURL(sessionId, investigationId),
        data: newEvent,
    })
        .then((response) => {
            console.log('The new event was created successfully on ICAT+ server.');
            //this.clearLocalStorage(NEW_EVENT_CONTEXT);
            onSuccess();
        })
        .catch((error) => {
            console.log(error);
        });
}

/**
 * Update the event on ICAT+ server
 * @param {*} newEvent event object to be created
 * @param {String} sessionId session Id required for HTTP request authentication
 * @param {*} investigationId investigation Id to which the event will be added to.
 * @param {*} onSuccess callback function executed after the asymchronous event creation process succeeded.
 */
export const updateEvent = (newEvent, sessionId, investigationId, onSuccess) => {
    axios({
        method: 'put',
        url: updateEventURL(sessionId, investigationId),
        data: { event: newEvent },
    })
        .then((response) => {
            console.log('the event was modified successfully on ICAT+ server.');
            onSuccess(response.data);
        })
        .catch((error) => {
            console.log(error);
        });
}

/**
 * Request all available tags associated to the given investigationId
 * @param {integer} investigationId investigation identifier 
 * @param {String} sessionId session identifier
 * @param {func} onError callback function executed when an error occured during the request.
 * @param {func} onSuccess callback function executed when the request succeeds.
 */
export const getTagsByInvestigationId = (sessionId, investigationId, onSuccess, onError) => {
    if (investigationId && sessionId) {
        axios({
            method: 'get',
            url: getTagsByInvestigationIdURL(sessionId, investigationId),
        })
            .then(data => onSuccess(data))
            .catch((error) => {
                console.log('ERROR] An error occured while retrieving the tag list. The error is ' + error);
                onError('An error occured while retrieving the tag list.');
            });

    } else {
        console.log('[ERROR] Missing parameters in the request handled by getEventsByInvestigationId()');
        onError('An error occured while retrieving the tag list.');
    };
}