import axios from 'axios';
import ElasticSearchQueryService from '../services/ElasticSearchQueryService';

const SEARCH_SERVER_URL = 'http://demo.searchkit.co/api/movies/_search';

const SEARCH_START = 'SEARCH_START';
const AGGREGATION_START = 'AGGREGATION_START';
const SEARCH = 'SEARCH';
const AGGREGATE = 'AGGREGATE';

export function search(searchQuery) {
    const elasticSearchQueryService = new ElasticSearchQueryService();

    return (dispatch) => {
        dispatch({
            type: SEARCH_START,
            payload: searchQuery,
        });

        dispatch({
            type: SEARCH,
            payload: axios.post(
                SEARCH_SERVER_URL,
                elasticSearchQueryService.getSearchQueryBody(searchQuery)
            ),
        });
    };
}

export function aggregatre(searchQuery, aggregationSelection) {
    const elasticSearchQueryService = new ElasticSearchQueryService();

    return (dispatch) => {
        dispatch({
            type: AGGREGATION_START,
            payload: aggregationSelection,
        });

        dispatch({
            type: AGGREGATE,
            payload: axios.post(
                SEARCH_SERVER_URL,
                elasticSearchQueryService.getSearchQueryBody(searchQuery, aggregationSelection)
            ),
        });
    };
}
