package zendeskapi.models.search;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonProperty;
import zendeskapi.exception.ZendeskApiException;
import zendeskapi.extensions.JsonHelper;
import zendeskapi.models.ZendeskObject;
/**
*
* @author jgroth
*
*/
public class SearchResults implements ZendeskObject {
@JsonProperty("count")
private Integer count;
@JsonProperty("next_page")
private Integer nextPage;
@JsonProperty("previous_page")
private Integer previousPage;
@JsonProperty("facets")
private String facets;
/**
* May consist of Tickets, Users, Groups, Organizations, and Topics. A
* result_type value is added to each result object and can have the
* following values: ticket, user, group, organization, topic.
* The object will consist of a LinkedHashMap<String, String>.
*/
@JsonProperty("results")
private List<Object> results;
private static Set<String> VALID_SEARCH_CLASSES = new HashSet<String>();
static {
VALID_SEARCH_CLASSES.add("ticket");
VALID_SEARCH_CLASSES.add("user");
VALID_SEARCH_CLASSES.add("group");
VALID_SEARCH_CLASSES.add("organization");
VALID_SEARCH_CLASSES.add("topic");
}
/**
*
* @param objectClass
* @return List of objectClass
* @throws ZendeskApiException
*/
public <T extends Object> List<T> getEntitiesFromSearch(Class<T> objectClass) throws ZendeskApiException {
String nameOfClass = objectClass.getName().replaceFirst(".*\\.", "").toLowerCase();
if (!VALID_SEARCH_CLASSES.contains(nameOfClass)) {
throw new ZendeskApiException("Class " + objectClass.getName() + " is not supported by the search API");
}
List<T> entities = new ArrayList<T>();
for (Object result : results) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) result;
if (map.get("result_type").contentEquals(nameOfClass)) {
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.putAll(map);
resultMap.remove("result_type");
try {
String json = JsonHelper.getJsonString(resultMap);
entities.add(JsonHelper.unmarshal(json, objectClass));
} catch (Exception e) {
throw new ZendeskApiException(e);
}
}
}
if (entities.size() > 0) {
return entities;
}
return null;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getNextPage() {
return nextPage;
}
public void setNextPage(Integer nextPage) {
this.nextPage = nextPage;
}
public Integer getPreviousPage() {
return previousPage;
}
public void setPreviousPage(Integer previousPage) {
this.previousPage = previousPage;
}
public List<Object> getResults() {
return results;
}
public void setResults(List<Object> results) {
this.results = results;
}
public String getFacets() {
return facets;
}
public void setFacets(String facets) {
this.facets = facets;
}
}