import {API_SERVER} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_ORDERS,
    RECEIVE_ORDERS
} from '../../constants/dashboardConstants';
import {fromWCOrder} from '../../helpers/OrderHelper';
import { MAX_ORDER_COUNT } from '../../constants/ordersConstants';
const htmlClient = new HtmlClient();

export const requestOrders = () => ({
    type: REQUEST_ORDERS,
    isLoading: true
});

export const recieveOrders = (json) => ({
        type: RECEIVE_ORDERS,
        isLoading: false,
        orders: json
});

export const fetchOrders = (viewAllOrders) => {
    return dispatch => {
        dispatch(requestOrders());
        return htmlClient.fetch({
                url: `${API_SERVER}/wp-json/wc/v2/orders?per_page=${MAX_ORDER_COUNT}&wiaas_is_active=1`,
                method: 'get',
            })
            .then(response => {
                dispatch(recieveOrders(response.data.map(wcOrder => fromWCOrder(wcOrder))));
            })
            .catch(error => {
                htmlClient.onError(error, dispatch);
            });
    }
}
