package org.nanopub.extra.security;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.nanopub.NanopubImpl;
import org.openrdf.OpenRDFException;
import org.openrdf.model.Statement;
import org.openrdf.model.vocabulary.FOAF;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.helpers.RDFHandlerBase;
import org.openrdf.rio.turtle.TurtleParser;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;

import net.trustyuri.TrustyUriUtils;

public class GetIntroNanopub {

	@com.beust.jcommander.Parameter(description = "user-id", required = true)
	private List<String> userIds;

	public static void main(String[] args) {
		NanopubImpl.ensureLoaded();
		GetIntroNanopub obj = new GetIntroNanopub();
		JCommander jc = new JCommander(obj);
		try {
			jc.parse(args);
		} catch (ParameterException ex) {
			jc.usage();
			System.exit(1);
		}
		try {
			obj.run();
		} catch (Exception ex) {
			ex.printStackTrace();
			System.exit(1);
		}
	}

	public static String get(String userId) throws IOException, OpenRDFException {
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
				.setConnectionRequestTimeout(100).setSocketTimeout(10000).build();
		HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
		return get(userId, c);
	}

	public static String get(final String userId, HttpClient httpClient) throws IOException, OpenRDFException {
		HttpGet get = new HttpGet(userId);
		get.setHeader("Accept", "text/turtle");
		InputStream in = null;
		try {
			HttpResponse resp = httpClient.execute(get);
			if (!wasSuccessful(resp)) {
				EntityUtils.consumeQuietly(resp.getEntity());
				throw new IOException(resp.getStatusLine().toString());
			}
			in = resp.getEntity().getContent();
			IntroExtractor ie = new IntroExtractor(userId);
			TurtleParser parser = new TurtleParser();
			parser.setRDFHandler(ie);
			parser.parse(in, userId);
			return ie.getIntroNanopubUri();
		} finally {
			if (in != null) in.close();
		}
	}

	private static class IntroExtractor extends RDFHandlerBase {

		private String userId;
		private String introNanopubUri;

		public IntroExtractor(String userId) {
			this.userId = userId;
		}

		public void handleStatement(Statement st) throws RDFHandlerException {
			if (introNanopubUri != null) return;
			if (!st.getSubject().stringValue().equals(userId)) return;
			if (!st.getPredicate().stringValue().equals(FOAF.PAGE.stringValue())) return;
			String o = st.getObject().stringValue();
			if (TrustyUriUtils.isPotentialTrustyUri(o)) {
				introNanopubUri = o;
			}
		};

		public String getIntroNanopubUri() {
			return introNanopubUri;
		}
	}
	
	private static boolean wasSuccessful(HttpResponse resp) {
		int c = resp.getStatusLine().getStatusCode();
		return c >= 200 && c < 300;
	}

	private void run() throws IOException, OpenRDFException {
		for (String userId : userIds) {
			System.out.print(userId + ": ");
			System.out.println(get(userId));
		}
	}

}

@@ -409,20 +409,125 @@
 .Nanopub
-Impl
+;%0Aimport org.nanopub.NanopubImpl;%0Aimport org.nanopub.NanopubUtils;%0Aimport org.nanopub.extra.server.GetNanopub
 ;%0Aimport
@@ -635,16 +635,50 @@
 y.FOAF;%0A
+import org.openrdf.rio.RDFFormat;%0A
 import o
@@ -1442,30 +1442,31 @@
 blic static 
-String
+Nanopub
  get(String 
@@ -1799,22 +1799,23 @@
  static 
-String
+Nanopub
  get(fin
@@ -2421,19 +2421,16 @@
 oNanopub
-Uri
 ();%0A%09%09%7D 
@@ -2576,22 +2576,23 @@
 private 
-String
+Nanopub
  introNa
@@ -2596,19 +2596,16 @@
 oNanopub
-Uri
 ;%0A%0A%09%09pub
@@ -2762,19 +2762,16 @@
 oNanopub
-Uri
  != null
@@ -3036,15 +3036,28 @@
 opub
-Uri = o
+ = GetNanopub.get(o)
 ;%0A%09%09
@@ -3074,22 +3074,23 @@
 %09public 
-String
+Nanopub
  getIntr
@@ -3097,19 +3097,16 @@
 oNanopub
-Uri
 () %7B%0A%09%09%09
@@ -3124,19 +3124,16 @@
 oNanopub
-Uri
 ;%0A%09%09%7D%0A%09%7D
@@ -3376,74 +3376,74 @@
 %0A%09%09%09
-System.out.print(userId + %22: %22);%0A%09%09%09System.out.println(get(userId)
+NanopubUtils.writeToStream(get(userId), System.out, RDFFormat.TRIG
 );%0A%09

Return entire nanopub instead of just URI