package eu.dnetlib.data.collector.plugins.ariadneplus.ehri;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import eu.dnetlib.rmi.data.CollectorServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * IDs of units are retrieved from the EHRI GraphQL API, see docs at https://portal.ehri-project.eu/api/graphql
 *
 * Created by Alessia Bardi on 19/04/2017.
 *
 * @author Alessia Bardi
 */
public class EHRIGraphQLClient {

	private static final Log log = LogFactory.getLog(EHRIGraphQLClient.class);

	public Iterator<String> collect(final String baseURL, final String graphQLQuery) throws URISyntaxException, IOException, CollectorServiceException {
		/*
		The curl equivalent:
		curl --header X-Stream:true \
        --header Content-type:application/json \
        https://portal.ehri-project.eu/api/graphql \
        --data-binary '{"query":"{topLevelDocumentaryUnits{items{id}}}"}'
		 */
		CloseableHttpClient httpClient = HttpClients.createDefault();
		URI baseURI = new URI(baseURL);
		HttpPost httpPost = new HttpPost();
		httpPost.setURI(baseURI);
		httpPost.setHeader("X-Stream", "true");
		httpPost.setHeader("Content-type", "application/json" );
		log.info(graphQLQuery);
		StringEntity postQuery = new StringEntity(graphQLQuery);
		httpPost.setEntity(postQuery);
		HttpEntity entity = null;
		try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
			switch(response.getStatusLine().getStatusCode()){
			case 200:
				entity = response.getEntity();
				InputStreamReader reader = new InputStreamReader(entity.getContent());
				return getIdentifiers(reader);
			default:
				log.error(httpPost);
				log.error(response.getStatusLine());
				throw new CollectorServiceException(response.getStatusLine().toString());
			}
		} finally {
			if(entity != null) EntityUtils.consume(entity);
		}
	}

	protected Iterator<String> getIdentifiers(final InputStreamReader input){
		JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
		JsonArray items = jsonObject.getAsJsonObject("data").getAsJsonObject("topLevelDocumentaryUnits").getAsJsonArray("items");
		log.debug(items);
		return Lists.newArrayList(Iterables.transform(items, jelem -> jelem.getAsJsonObject().get("id").getAsString())).iterator();
	}

}
