import { fetch } from '../../utils/dataAccess';

export function loading(loading) {
    return { type: 'SALES_BY_GRANULARITY_LOADING', loading };
}

export function updateFilter(granularity, lowerBound, upperBound) {
    return { type: 'SALES_BY_GRANULARITY_UPDATE_FILTER', granularity, lowerBound, upperBound };
}

export function success(retrieved) {
    return { type: 'SALES_BY_GRANULARITY_SUCCESS', retrieved };
}

export function error(error) {
    return { type: 'SALES_BY_GRANULARITY_ERROR', error };
}

export function fetchData(granularity, lowerBound, upperBound) {
    return dispatch => {
        dispatch(loading(true));

        const url = `property_sales/sales_by_granularity?granularity=${encodeURIComponent(granularity)}&date_start=${encodeURIComponent(lowerBound)}&date_end=${encodeURIComponent(upperBound)}`;

        return fetch(url, { method: "GET" })
            .then(res => {
                dispatch(loading(false));

                return res.json();
            })
            .then(retrieved => dispatch(success(retrieved)))
            .catch(e => {
                dispatch(loading(false));

                dispatch(error(e.message));
            });
    };
}
