package eu.dnetlib.data.collector.plugins.datasets;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ElasticSearchResponse {

	/** The logger. */
	private static final Log log = LogFactory.getLog(ElasticSearchResponse.class);
	private long total;
	private List<String> xmlRecords;

	public static ElasticSearchResponse createNewResponse(final String response) {
		ElasticSearchResponse item = new ElasticSearchResponse();

		if (response == null) {
			log.fatal("Error: null elasticsearch reponse");
			return null;

		}
		JsonElement jElement = new JsonParser().parse(response);
		JsonObject jobject = jElement.getAsJsonObject();
		if (jobject.has("hits")) {

			item.setTotal(jobject.get("hits").getAsJsonObject().get("total").getAsLong());

			JsonElement hits = ((JsonObject) jobject.get("hits")).get("hits");

			JsonArray hitsObject = hits.getAsJsonArray();

			List<String> records = new ArrayList<String>();

			for (JsonElement elem : hitsObject) {
				JsonObject _source = (JsonObject) ((JsonObject) elem).get("_source");
				String xml = _source.get("xml").getAsString();
				records.add(xml);
			}
			item.setXmlRecords(records);
			return item;
		}
		return null;
	}

	/**
	 * @return the xmlRecords
	 */
	public List<String> getXmlRecords() {
		return xmlRecords;
	}

	/**
	 * @param xmlRecords
	 *            the xmlRecords to set
	 */
	public void setXmlRecords(final List<String> xmlRecords) {
		this.xmlRecords = xmlRecords;
	}

	/**
	 * @return the total
	 */
	public long getTotal() {
		return total;
	}

	/**
	 * @param total
	 *            the total to set
	 */
	public void setTotal(final long total) {
		this.total = total;
	}

}
