import {
    API_SERVER
} from '../../config';
import {
    orderMessages,
    REQUEST_ORDER_INFO,
    RECEIVE_ORDER_INFO,
    SEND_ORDER_COMMENT,
    REQUEST_CUSTOMER_DOCUMENTS,
    RECEIVE_CUSTOMER_DOCUMENTS,
    RE_UPLOAD_DOCUMENT,
    REQUEST_VALIDATION_COMMENTS,
    RECEIVE_VALIDATION_COMMENTS,
    REQUEST_IS_NEXT_STEP_WANTED,
    RECEIVE_IS_NEXT_STEP_WANTED,
    RECEIVE_IS_COMPONENT_DISABLED,
    SET_EARLIEST_INSTALLATION_DATE,
    SET_CONFIRMATION_DATES,
    REQUEST_INSTALLATION_COMPANIES,
    RECEIVE_INSTALLATION_COMPANIES,
    REQUEST_ALL_SHIPPING_DATES_CONFIRMED,
    RECEIVE_ALL_SHIPPING_DATES_CONFIRMED,
    SET_SUPPORT_MESSAGE,
    SET_SCHEDULING_DISABLED_FLAG
} from '../../constants/ordersConstants';
import HtmlClient from '../../helpers/HtmlClient';
import {updateMessages} from '../notification/notificationActions';

const htmlClient = new HtmlClient();

const requestOrderInfo = () => ({
    type: REQUEST_ORDER_INFO,
    isLoading: true
});
const recieveOrderInfo = (json) => ({
    type: RECEIVE_ORDER_INFO,
    isLoading: false,
    orderInfo: json
});

export const fetchOrderInfo = (idOrder) => {
    return dispatch => {
        dispatch(requestOrderInfo());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getOrderInfo`,
                method: 'post',
                data: {
                    idOrder
                }
            })
            .then(response => {
                if (response.data) {
                    dispatch(recieveOrderInfo(response.data));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

const sendComment = () => ({
    type: SEND_ORDER_COMMENT
})

export const addComment = (idOrder, comment) => {
    return dispatch => {
        dispatch(sendComment());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/addOrderComment`,
                method: 'post',
                data: {
                    idOrder,
                    comment
                }
            })
            .then(response => {
                if (response.data && response.data.messages) {
                    dispatch(updateMessages(response.data.messages, orderMessages));
                    dispatch(fetchOrderInfo(idOrder));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

const requestCustomerDocuments = () => ({
    type: REQUEST_CUSTOMER_DOCUMENTS
});
const recieveCustomerDocuments = (json) => ({
    type: RECEIVE_CUSTOMER_DOCUMENTS,
    customerDocuments: json
});

export const fetchCustomerDocuments = (idOrder, documentType, idPackage = 0) => {
    return dispatch => {
        dispatch(requestCustomerDocuments());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getOrderDocumentsPerType`,
                method: 'post',
                data: {
                    idOrder,
                    idPackage,
                    documentType
                }
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'documents' in response.data) {
                    dispatch(recieveCustomerDocuments(response.data.documents));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

const requestValidationComments = () => ({
    type: REQUEST_VALIDATION_COMMENTS
});
const recieveValidationComments = (json) => ({
    type: RECEIVE_VALIDATION_COMMENTS,
    validationComments: json
});

export const fetchValidationComments = (idOrder, idProcessStep, commentType) => {
    return dispatch => {
        dispatch(requestValidationComments());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getCommentsByType`,
                method: 'post',
                data: {
                    idOrder,
                    idProcessStep,
                    commentType
                }
            })
            .then(response => {
                if (response.data) {
                    dispatch(recieveValidationComments(response.data));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

export const reUploadDocumnet = () => ({
    type: RE_UPLOAD_DOCUMENT
});

export const reUploadOrderDocument = (idPackage, idOrder, idDocument, file) => {
    return dispatch => {
        dispatch(reUploadDocumnet());
        return htmlClient.uploadFile(file, {
            url: `${API_SERVER}/orders/api/reUploadQuestionaire`,
            data: {
                idPackage,
                idOrder,
                idDocument
            }
        }).then(response => {
            if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                dispatch(updateMessages(response.data.messages, orderMessages));
                dispatch(fetchCustomerDocuments(idOrder, 'orderQuestionaire', idPackage));
            }
        }).catch(error => {
            htmlClient.onError(error, dispatch);
        });
    }
}

export const badFile = () =>{
    return dispatch => {
        dispatch(updateMessages([{code: 'warning', message: 'INVALID_FILE_QUESTIONNAINRE'}], orderMessages));
    }
}

export const requestIsNextStepWanted = () => ({type: REQUEST_IS_NEXT_STEP_WANTED});
export const receiveIsNextStepWanted = (json) => ({
    type: RECEIVE_IS_NEXT_STEP_WANTED,
    isNextStepWanted: json
});

const receiveIsComponentDisabled = (isComponentDisabled) => ({
    type: RECEIVE_IS_COMPONENT_DISABLED,
    isComponentDisabled
});

const setEarliestInstallationDate = (earliestInstallDate) => ({
    type: SET_EARLIEST_INSTALLATION_DATE,
    earliestInstallDate
});

const setConfirmationDates = (json) => ({
    type: SET_CONFIRMATION_DATES,
    confirmationDates: json
});
export const getInstallationConfirmationDates = (idOrder, idPackage = 0) => {
    return dispatch => {
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getInstallationDates`,
                method: 'post',
                data: {idOrder, idPackage}
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'confirmationDates' in response.data) {
                    dispatch(setConfirmationDates(response.data.confirmationDates));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

const requestInstallationCompanies = () => ({type: REQUEST_INSTALLATION_COMPANIES});
const recieveInstallationCompanies = (json) => ({
    type: RECEIVE_INSTALLATION_COMPANIES,
    installCompanies: json
});

const requestAreAllShippingDatesConfirmed = ()=> ({type: REQUEST_ALL_SHIPPING_DATES_CONFIRMED});
const receiveAreAllShippingDatesConfirmed = (json) => ({
    type: RECEIVE_ALL_SHIPPING_DATES_CONFIRMED,
    areAllShippingDatesConfirmed: json
});

export const getAllDataForInstallation = (idOrder, usedForDirective, stepsNameForInstallation, fileType) => {
    const isNextStepTheOneWanted = {};
    return dispatch => {
    dispatch(requestInstallationCompanies());
        dispatch(requestIsNextStepWanted());
        dispatch(requestCustomerDocuments());
        dispatch(requestAreAllShippingDatesConfirmed());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getAllDataForInstallation`,
                method: 'post',
                data: {idOrder, stepsNameForInstallation, fileType}
            })
            .then(response => {
                if (typeof response.data !== 'undefined') {
                    if ('messages' in response.data) {
                        dispatch(updateMessages(response.data.messages, orderMessages));
                    }
                    if('installCompanies' in response.data) {
                        dispatch(recieveInstallationCompanies(response.data.installCompanies));
                    }
                    if('earliestInstallationDate' in response.data) {
                        dispatch(setEarliestInstallationDate(response.data.earliestInstallationDate));
                    }
                    if ('installationDates' in response.data) {
                        dispatch(setConfirmationDates(response.data.installationDates.confirmationDates));
                    }
                    if('isNextStepWanted' in response.data) {
                        isNextStepTheOneWanted[usedForDirective] = response.data.isNextStepWanted;

                        dispatch(receiveIsNextStepWanted(isNextStepTheOneWanted));
                        dispatch(receiveIsComponentDisabled(isNextStepTheOneWanted));
                    }
                    if('areAllShippingDatesConfirmed' in response.data) {
                        dispatch(receiveAreAllShippingDatesConfirmed(response.data.areAllShippingDatesConfirmed));
                    }
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    };
}

export const updateInstallationDate = (idOrder, idPackage, installationDate, status, clearDateInput='') => {
    return dispatch => {
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/updateInstallationDate`,
                method: 'post',
                data: {idOrder, idPackage, installationDate, status}
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                    dispatch(updateMessages(response.data.messages, orderMessages));
                    if(response.data.messages.find(messageObj => {return messageObj.code === 'success';})) {
                        if(clearDateInput) {
                            clearDateInput(undefined);
                        }
                    }
                }
                dispatch(getInstallationConfirmationDates(idOrder, idPackage));
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

export const removeMyDate = (idOrder, idPackage, installationDate) => {
    return dispatch => {
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/removeMyDate`,
                method: 'post',
                data: {idOrder, idPackage, installationDate}
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                    dispatch(updateMessages(response.data.messages, orderMessages));
                }
                dispatch(getInstallationConfirmationDates(idOrder, idPackage));
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

export const setSupportMessage = (message) => ({
    type: SET_SUPPORT_MESSAGE,
    supportText: message
});

export const sendSupportMail = (orderInfo, orderPackages, supportText) => {
    return dispatch => {
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/sendSupportMail`,
                method: 'post',
                data: {orderInfo, orderPackages, supportText}
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'messages' in response.data) {
                    dispatch(updateMessages(response.data.messages, orderMessages));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

export const setSchedulingFlag = (flag) => ({
    type: SET_SCHEDULING_DISABLED_FLAG,
    isSchedulingDisabled: flag
});
