import {API_SERVER} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_ORDER_PROJECTS,
    RECEIVE_ORDER_PROJECTS,
    REQUEST_ADD_PROJECT,
    orderProjectsTexts
} from '../../constants/orderProjectsConstants';
import {updateMessages} from '../notification/notificationActions';
import {setDialogOpenFlag} from '../dialog/dialogActions';

const htmlClient = new HtmlClient();

const requestOrderProjects = () => ({
    type: REQUEST_ORDER_PROJECTS,
    isLoading: true
});
const recieveOrderProjects = (json) => ({
    type: RECEIVE_ORDER_PROJECTS,
    isLoading: false,
    orderProjects: json
});

const generateOptions = (orderProjects) => {
    orderProjects.forEach((orderProject) => {
        orderProject.value = orderProject.id;
        orderProject.label = orderProject.name;
    });

    return orderProjects;
}

export const getOrderProjects = () => {
    return dispatch => {
        dispatch(requestOrderProjects());

        return htmlClient.fetch({
                url: `${API_SERVER}/wp-json/wiaas/order-projects`
            })
            .then(response => {
                if (response.data) {
                    const orderProjects = generateOptions(response.data);
                    dispatch(recieveOrderProjects(orderProjects));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

const requestAddProject = () => ({
    type: REQUEST_ADD_PROJECT,
    isLoading: true
});

export const addProject = (projectName) => {
    return dispatch => {
        dispatch(requestAddProject());
        return htmlClient.fetch({
                url: `${API_SERVER}/wp-json/wiaas/order-projects`,
                method: 'post',
                data: {
                    name: projectName
                }
            })
            .then(response => {
                if(response.data && response.data.messages){
                    dispatch(updateMessages(response.data.messages, orderProjectsTexts.messages));
                    if(response.data.messages[0].code === 'success'){
                        dispatch(getOrderProjects());
                        dispatch(setDialogOpenFlag(false));
                    }
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}
