import { helper } from '@appbaseio/reactivecore';

const { getAggsOrder } = helper;
const getAggsQuery = (query, props) => {
	const clonedQuery = { ...query };
	const { dataField, size, sortBy, showMissing, missingLabel } = props;
	clonedQuery.size = 0;
	clonedQuery.aggs = {
		[dataField]: {
			terms: {
				field: dataField,
				size,
				order: getAggsOrder(sortBy || 'count'),
				...(showMissing ? { missing: missingLabel } : {})
			}
		}
	};

	if (props.nestedField) {
		clonedQuery.aggs = {
			reactivesearch_nested: {
				nested: {
					path: props.nestedField
				},
				aggs: clonedQuery.aggs
			}
		};
	}

	return clonedQuery;
};

const getCompositeAggsQuery = (query, props, after) => {
	const clonedQuery = { ...query };
	// missing label not available in composite aggs
	const { dataField, size, sortBy, showMissing } = props;

	// composite aggs only allows asc and desc
	const order = sortBy === 'count' ? {} : { order: sortBy };

	clonedQuery.aggs = {
		[dataField]: {
			composite: {
				sources: [
					{
						[dataField]: {
							terms: {
								field: dataField,
								...order,
								...(showMissing ? { missing_bucket: true } : {})
							}
						}
					}
				],
				size,
				...after
			}
		}
	};

	if (props.nestedField) {
		clonedQuery.aggs = {
			reactivesearch_nested: {
				nested: {
					path: props.nestedField
				},
				aggs: clonedQuery.aggs
			}
		};
	}

	return clonedQuery;
};

export { getAggsQuery, getCompositeAggsQuery };

@@ -153,33 +153,35 @@
 uery %7D;%0A%09const %7B
- 
+%0A%09%09
 dataField, size,
@@ -214,17 +214,19 @@
 ingLabel
- 
+,%0A%09
 %7D = prop
@@ -431,25 +431,28 @@
  %7D : %7B%7D)
+,
 %0A%09%09%09%7D
+,
 %0A%09%09%7D
+,
 %0A%09%7D;%0A%0A%09i
@@ -560,32 +560,33 @@
 rops.nestedField
+,
 %0A%09%09%09%09%7D,%0A%09%09%09%09aggs
@@ -595,37 +595,67 @@
 clonedQuery.aggs
+,%0A%09%09%09%09size: clonedQuery.size,
 %0A%09%09%09%7D
+,
 %0A%09%09%7D;%0A%09%7D%0A%0A%09retur
@@ -823,17 +823,19 @@
 %09const %7B
- 
+%0A%09%09
 dataFiel
@@ -862,17 +862,19 @@
 wMissing
- 
+,%0A%09
 %7D = prop
@@ -1196,16 +1196,17 @@
  %7D : %7B%7D)
+,
 %0A%09%09%09%09%09%09%09
@@ -1210,16 +1210,17 @@
 %09%09%09%7D
+,
 %0A%09%09%09%09%09%09%7D
 %0A%09%09%09
@@ -1219,15 +1219,17 @@
 %09%09%09%7D
+,
 %0A%09%09%09%09%09%7D
+,
 %0A%09%09%09
@@ -1258,21 +1258,47 @@
 fter
+,
 %0A%09%09%09%7D
+,
 %0A%09%09%7D
+,
 %0A%09%7D;
+%0A%09clonedQuery.size = 0;
 %0A%0A%09i
@@ -1414,16 +1414,17 @@
 tedField
+,
 %0A%09%09%09%09%7D,%0A
@@ -1449,21 +1449,51 @@
 ery.aggs
+,%0A%09%09%09%09size: clonedQuery.size,
 %0A%09%09%09%7D
+,
 %0A%09%09%7D;%0A%09%7D

set query size to 0 for composite aggs #745