import {API_SERVER} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_ACTIVE_ORDERS,
    RECEIVE_ACTIVE_ORDERS,
    REQUEST_HISTORY_ORDERS,
    RECEIVE_HISTORY_ORDERS,
    SET_VIEW_ALL_ORDERS
} from '../../constants/ordersConstants';
const htmlClient = new HtmlClient();

const requestActiveOrders = () => ({
    type: REQUEST_ACTIVE_ORDERS,
    isLoading: true
});
const recieveActiveOrders = (json) => ({
    type: RECEIVE_ACTIVE_ORDERS,
    isLoading: false,
    activeOrders: json
});

export const getActiveOrders = () => {
    return dispatch => {
        dispatch(requestActiveOrders());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getActiveOrders`
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'orders' in response.data) {
                    dispatch(recieveActiveOrders(response.data.orders));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

const requestHistoryOrders = () => ({
    type: REQUEST_HISTORY_ORDERS,
    isLoading: true
});
const recieveHistoryOrders = (json) => ({
    type: RECEIVE_HISTORY_ORDERS,
    isLoading: false,
    historyOrders: json
});

export const getHistoryOrders = () => {
    return dispatch => {
        dispatch(requestHistoryOrders());
        return htmlClient.fetch({
                url: `${API_SERVER}/orders/api/getHistoryOrders`
            })
            .then(response => {
                if (typeof response.data !== 'undefined' && 'orders' in response.data) {
                    dispatch(recieveHistoryOrders(response.data.orders));
                }
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}

export const setViewAllOrdersFlag = (isViewAllOrdersChecked) => ({type: SET_VIEW_ALL_ORDERS, isViewAllOrdersChecked});
