package org.opencds.cqf.cql.retrieve;

import java.util.ArrayList;
import java.util.List;

import org.hl7.fhir.instance.model.Bundle;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.client.api.IGenericClient;

public class RestFhirRetrieveProvider extends FhirRetrieveProvider {

	protected String endpoint;
	protected IGenericClient fhirClient;
	protected FhirContext fhirContext;

	public RestFhirRetrieveProvider(FhirContext fhirContext, String endpoint) {
		this.endpoint = endpoint;
		this.fhirContext = fhirContext;
        this.fhirClient = fhirContext.newRestfulGenericClient(endpoint);
	}

	@Override
	protected Iterable<Object> executeQueries(String dataType, List<SearchParameterMap> queries) {
		// No filters for the the dataType.
		List<Bundle> bundles = new ArrayList<Bundle>();
		if (queries.size() == 0) {
			bundles.add(
				this.fhirClient.search().forResource(dataType)
					.returnBundle(org.hl7.fhir.instance.model.Bundle.class).execute());
		}
		else {
			for (SearchParameterMap map : queries) {
				Bundle bundle = this.fhirClient.search().byUrl(dataType + map.toNormalizedQueryString(this.fhirContext))
					.returnBundle(org.hl7.fhir.instance.model.Bundle.class).execute();
				bundles.add(bundle);
			}
		}

		return new FhirBundlesCursor(fhirClient, bundles, dataType);
	}
}

@@ -60,16 +60,46 @@
 ayList;%0A
+import java.util.Collections;%0A
 import j
@@ -807,277 +807,194 @@
 %7B%0A%09%09
-// No filters for the the dataType.%0A%09%09List%3CBundle%3E bundles = new ArrayList%3CBundle%3E();%0A%09%09if (queries.size() == 0) %7B%0A%09%09%09bundles.add(%0A%09%09%09%09this.fhirClient.search().forResource(dataType)%0A%09%09%09%09%09.returnBundle(org.hl7.fhir.instance.model.Bundle.class).execute());%0A%09%09%7D%0A%09%09else %7B%0A%09
+if (queries == null %7C%7C queries.isEmpty()) %7B%0A            return Collections.emptyList();%0A        %7D%0A%09%09// No filters for the the dataType.%0A%09%09List%3CBundle%3E bundles = new ArrayList%3CBundle%3E();%0A
 %09%09fo
@@ -1032,17 +1032,16 @@
 ries) %7B%0A
-%09
 %09%09%09Bundl
@@ -1140,17 +1140,16 @@
 ntext))%0A
-%09
 %09%09%09%09.ret
@@ -1214,17 +1214,16 @@
 e();%0A%09%09%09
-%09
 bundles.
@@ -1239,13 +1239,8 @@
 e);%0A
-%09%09%09%7D%0A
 %09%09%7D%0A

Update REST retriever to return empty set if no queries exist