import {
    API_SERVER
} from '../../config';
import HtmlClient from '../../helpers/HtmlClient';
import {
    REQUEST_SET_BID,
    bidsTexts
} from '../../constants/bidsConstants';
import {fetchCartItems} from '../cart/cartActions';
import {updateMessages} from '../notification/notificationActions';
import {setDialogOpenFlag} from '../../actions/dialog/dialogActions';

const client = new HtmlClient();

const requestSetBid = () => ({
    type: REQUEST_SET_BID
});

export const setBid = (idBid, idCart) => {
    return dispatch => {
        dispatch(requestSetBid());
        return client.fetch({
                url: `${API_SERVER}/cart/api/setBidForCart`,
                method: 'post',
                data: {idBid, idCart}
            })
            .then(response => {
                if(response.data && response.data.messages){
                    dispatch(updateMessages(response.data.messages, bidsTexts.messages));
                    if(response.data.messages[0].code === 'success'){
                        dispatch(setDialogOpenFlag(false));
                        dispatch(fetchCartItems(true));
                    }
                }
            })
            .catch(error => {
                client.onError(error, dispatch);
            });
    }
};
