import { createHandlerChainRunnerOptionalParameter, HandlerWithResult } from "@insite/client-framework/HandlerCreator";
import { isLoadMore } from "@insite/client-framework/Store/Pages/ProductList/ProductListSelectors";
import cloneDeep from "lodash/cloneDeep";
import qs from "qs";

type HandlerType = HandlerWithResult<{}, string>;

export const SetFilterQuery: HandlerType = props => {
    const queryObject = cloneDeep(props.getState().pages.productList.productFilters);
    delete queryObject.expand;
    delete queryObject.pageCategoryId;
    delete queryObject.pageProductLineId;
    delete queryObject.pageBrandId;

    if (isLoadMore(props.getState())) {
        delete queryObject.pageSize;
    }

    if (queryObject.searchWithinQueries && queryObject.searchWithinQueries.length > 1) {
        // Search within Queries need to split by space, to use for ElasticSearch
        queryObject.searchWithinQueries = [queryObject.searchWithinQueries.join(" ")];
    }
    props.result = qs.stringify(queryObject, { arrayFormat: "comma", skipNulls: true });
};

export const DispatchSetFilterQuery: HandlerType = props => {
    props.dispatch({
        type: "Pages/ProductList/SetFilterQuery",
        result: props.result,
    });
};

export const chain = [SetFilterQuery, DispatchSetFilterQuery];

const setFilterQuery = createHandlerChainRunnerOptionalParameter(chain, {}, "SetFilterQuery");
export default setFilterQuery;
