package org.nanopub.extra.server;

import java.io.OutputStream;

import org.nanopub.Nanopub;
import org.nanopub.NanopubUtils;
import org.nanopub.extra.index.NanopubIndex;
import org.openrdf.model.URI;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;

public class FetchIndexFromDb extends FetchIndex {

	public static final int maxParallelRequestsPerServer = 5;

	private String indexUri;
	private NanopubDb db;
	private OutputStream out;
	private RDFFormat format;
	private boolean writeIndex, writeContent;
	private int nanopubCount;
	private FetchIndex.Listener listener;

	public FetchIndexFromDb(String indexUri, NanopubDb db, OutputStream out, RDFFormat format, boolean writeIndex, boolean writeContent) {
		this.indexUri = indexUri;
		this.db = db;
		this.out = out;
		this.format = format;
		this.writeIndex = writeIndex;
		this.writeContent = writeContent;
		nanopubCount = 0;
	}

	public void run() {
		try {
			getIndex(indexUri);
		} catch (RDFHandlerException ex) {
			throw new RuntimeException(ex);
		}
	}

	private void getIndex(String indexUri) throws RDFHandlerException {
		Nanopub np = GetNanopub.get(indexUri, db);
		if (!(np instanceof NanopubIndex)) {
			throw new RDFHandlerException("Nanopublication index expected");
		}
		NanopubIndex npi = (NanopubIndex) np;
		if (writeIndex) {
			writeNanopub(npi);
		}
		if (writeContent) {
			for (URI elementUri : npi.getElements()) {
				writeNanopub(GetNanopub.get(elementUri.toString(), db));
			}
		}
		for (URI subIndexUri : npi.getSubIndexes()) {
			getIndex(subIndexUri.toString());
		}
		if (npi.getAppendedIndex() != null) {
			getIndex(npi.getAppendedIndex().toString());
		}
	}

	private void writeNanopub(Nanopub np) throws RDFHandlerException {
		nanopubCount++;
		if (listener != null && nanopubCount % 100 == 0) {
			listener.progress(nanopubCount);
		}
		NanopubUtils.writeToStream(np, out, format);
	}

	public int getNanopubCount() {
		return nanopubCount;
	}

	public void setProgressListener(Listener l) {
		listener = l;
	}

}

@@ -58,16 +58,62 @@
 tream;%0A%0A
+import org.nanopub.MalformedNanopubException;%0A
 import o
@@ -196,28 +196,120 @@
 a.index.
-NanopubIndex
+IndexUtils;%0Aimport org.nanopub.extra.index.NanopubIndex;%0Aimport org.nanopub.extra.index.NanopubIndexImpl
 ;%0Aimport
@@ -1133,16 +1133,44 @@
 ception 
+%7C MalformedNanopubException 
 ex) %7B%0A%09%09
@@ -1272,24 +1272,51 @@
 lerException
+, MalformedNanopubException
  %7B%0A%09%09Nanopub
@@ -1362,35 +1362,29 @@
 f (!
-(np instanceof Nanopub
+IndexUtils.is
 Index
+(np
 )) %7B
@@ -1398,25 +1398,22 @@
 ow new R
-DFHandler
+untime
 Exceptio
@@ -1420,38 +1420,36 @@
 n(%22N
-anopublication index expected%22
+OT AN INDEX: %22 + np.getUri()
 );%0A%09
@@ -1476,25 +1476,34 @@
 i = 
-(Nanopub
+IndexUtils.castTo
 Index
-) 
+(
 np
+)
 ;%0A%09%09

Fix bug with nanopub index object