package org.gcube.data.analysis.nlphub.mapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Set;

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

import org.gcube.data.analysis.nlphub.legacy.NerAlgorithm;
import org.gcube.data.analysis.nlphub.legacy.NerAnnotationData;
import org.gcube.data.analysis.nlphub.legacy.NerEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultMapper implements JsonMapper {
	private static final Logger logger = LoggerFactory.getLogger(DefaultMapper.class);

	public String getJson(String alg, String link) {
		NerAlgorithm algInfo = new NerAlgorithm(alg);
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(link).openConnection();
			connection.setRequestMethod("GET");
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			JsonObject jsonRoot = (JsonObject) new JsonParser().parse(reader);
			JsonElement entities = jsonRoot.get("entities");
			if ((entities != null) && (entities.isJsonObject())) {
				JsonObject e = (JsonObject) entities;
				Set<String> properties = e.keySet();
				for (String p : properties) {
					JsonElement property = e.get(p);
					if (!property.isJsonArray())
						continue;
					NerAnnotationData data = new NerAnnotationData(p);
					JsonArray jsonAnnotation = (JsonArray) property;
					int size = jsonAnnotation.size();
					for (int i = 0; i < size; i++) {
						JsonElement ann = jsonAnnotation.get(i);
						if (ann.isJsonObject()) {
							JsonObject annotation = (JsonObject) ann;
							Set<String> fields = annotation.keySet();
							JsonArray indices = (JsonArray) annotation.get("indices");
							NerEntity ne = new NerEntity(indices.get(0).getAsInt(), indices.get(1).getAsInt());

							for (String f : fields) {
								if (f.equals("indices"))
									continue;
								JsonElement je = annotation.get(f);
								if (!je.isJsonArray() && !je.isJsonObject() && !je.isJsonNull()) {
									ne.addProperty(f, je.getAsString());
								}
							}
							data.addNerEntity(ne);
						}
					}
					algInfo.addAnnotationData(data);
				}
			}
			return algInfo.toJson().toString();
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
			return null;
		}
	}
	
}
