import {
    API_SERVER
} from '../../config';
import { fromWiaasCustomerQuestionnaire } from '../../helpers/ProcessHelper';


import {
    UPLOAD_CUSTOMER_QUESTIONNAIRE,
    REQUEST_CUSTOMER_QUESTIONNAIRES,
    RECEIVE_CUSTOMER_QUESTIONNAIRES,
    orderMessages, REQUEST_CUSTOMER_ACCEPTANCE, RECEIVE_CUSTOMER_ACCEPTANCE, UPLOAD_CUSTOMER_ACCEPTANCE
} from '../../constants/ordersConstants';

import {
    updateMessages
} from '../notification/notificationActions';
import HtmlClient from '../../helpers/HtmlClient';
import {fetchCustomerAcceptance} from "./customerAcceptanceActions";

const htmlClient = new HtmlClient();


const requestCustomerQuestionnaires = () => ({
    type: REQUEST_CUSTOMER_QUESTIONNAIRES
});

const receiveCustomerQuestionnaires = (json) => ({
    type: RECEIVE_CUSTOMER_QUESTIONNAIRES,
    customerQuestionnaires: json
});

const uploadCustomerQuestionnaireAction = () => ({
    type: UPLOAD_CUSTOMER_QUESTIONNAIRE
});


export const fetchCustomerQuestionnaires = (idOrder) => {
    return dispatch => {
        dispatch(requestCustomerQuestionnaires());
        return htmlClient.fetch({
            url: `${API_SERVER}/wp-json/wiaas/delivery/${idOrder}/customer-questionnaires`,
            method: 'get'
        })
            .then(response => {
                if (typeof response.data !== 'undefined') {
                    const questionnairesData = response.data.map(cData => fromWiaasCustomerQuestionnaire(cData));
                    dispatch(receiveCustomerQuestionnaires(questionnairesData));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

export const uploadCustomerQuestionnaire = (orderId, actionId, file) => {

    return dispatch => {
        dispatch(uploadCustomerQuestionnaireAction());
        return htmlClient.uploadFile(file, {
            url: `${API_SERVER}/wp-json/wiaas/delivery/${orderId}/customer-questionnaires/upload/${actionId}`,
        }).then(response => {
            if (typeof response.data !== 'undefined') {
                dispatch(updateMessages(response.data.messages, orderMessages));
                dispatch(fetchCustomerQuestionnaires(orderId));
            }
        }).catch(error => {
            htmlClient.onError(error, dispatch);
        });
    }
}