package org.petapico.npop;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

import net.trustyuri.TrustyUriException;

import org.nanopub.MalformedNanopubException;
import org.nanopub.MultiNanopubRdfHandler;
import org.nanopub.MultiNanopubRdfHandler.NanopubHandler;
import org.nanopub.Nanopub;
import org.nanopub.NanopubImpl;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.Rio;

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

public class Topic {

	@com.beust.jcommander.Parameter(description = "input-nanopubs", required = true)
	private List<File> inputNanopubs = new ArrayList<File>();

	@com.beust.jcommander.Parameter(names = "-o", description = "Output file")
	private File outputFile;

	@com.beust.jcommander.Parameter(names = "--in-format", description = "Format of the input nanopubs: trig, nq, trix, trig.gz, ...")
	private String inFormat;

	@com.beust.jcommander.Parameter(names = "-u", description = "Include the nanopub URI in output")
	private boolean outputNanopubUri = false;

	public static void main(String[] args) {
		NanopubImpl.ensureLoaded();
		Topic obj = new Topic();
		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);
		}
	}

	private RDFFormat rdfInFormat;
	private OutputStream outputStream = System.out;
	private BufferedWriter writer;

	private void run() throws IOException, RDFParseException, RDFHandlerException,
			MalformedNanopubException, TrustyUriException {
		for (File inputFile : inputNanopubs) {
			if (inFormat != null) {
				rdfInFormat = Rio.getParserFormatForFileName("file." + inFormat);
			} else {
				rdfInFormat = Rio.getParserFormatForFileName(inputFile.toString());
			}
			if (outputFile != null) {
				if (outputFile.getName().endsWith(".gz")) {
					outputStream = new GZIPOutputStream(new FileOutputStream(outputFile));
				} else {
					outputStream = new FileOutputStream(outputFile);
				}
			}

			writer = new BufferedWriter(new OutputStreamWriter(outputStream));

			MultiNanopubRdfHandler.process(rdfInFormat, inputFile, new NanopubHandler() {

				@Override
				public void handleNanopub(Nanopub np) {
					try {
						process(np);
					} catch (RDFHandlerException ex) {
						throw new RuntimeException(ex);
					} catch (IOException ex) {
						throw new RuntimeException(ex);
					}
				}

			});

			writer.flush();
			if (outputStream != System.out) {
				writer.close();
			}
		}
	}

	private void process(Nanopub np) throws RDFHandlerException, IOException {
		writer.write(getTopic(np) + "");
		if (outputNanopubUri) {
			writer.write(" " + np.getUri());
		}
		writer.write("\n");
	}

	public static Resource getTopic(Nanopub np) {
		Map<Resource,Integer> resourceCount = new HashMap<>();
		for (Statement st : np.getAssertion()) {
			Resource subj = st.getSubject();
			if (subj.equals(np.getUri())) continue;
			if (!resourceCount.containsKey(subj)) resourceCount.put(subj, 0);
			resourceCount.put(subj, resourceCount.get(subj) + 1);
		}
		int max = 0;
		Resource topic = null;
		for (Resource r : resourceCount.keySet()) {
			int c = resourceCount.get(r);
			if (c > max) {
				topic = r;
				max = c;
			} else if (c == max) {
				topic = null;
			}
		}
		return topic;
	}

}

@@ -1162,16 +1162,161 @@
 tFile;%0A%0A
+%09@com.beust.jcommander.Parameter(names = %22-i%22, description = %22Property URIs (separated by blanks) to ignore%22)%0A%09private String ignoreProperties;%0A%0A
 %09@com.be
@@ -1439,16 +1439,16 @@
 , ...%22)%0A
-
 %09private
@@ -2060,16 +2060,71 @@
  writer;
+%0A%09private Map%3CString,Boolean%3E ignore = new HashMap%3C%3E();
 %0A%0A%09priva
@@ -2248,16 +2248,159 @@
 ption %7B%0A
+%09%09if (ignoreProperties != null) %7B%0A%09%09%09for (String s : ignoreProperties.trim().split(%22 %22)) %7B%0A%09%09%09%09if (!s.isEmpty()) ignore.put(s, true);%0A%09%09%09%7D%0A%09%09%7D%0A
 %09%09for (F
@@ -3452,16 +3452,24 @@
 Topic(np
+, ignore
 ) + %22%22);
@@ -3600,24 +3600,52 @@
 c(Nanopub np
+, Map%3CString,Boolean%3E ignore
 ) %7B%0A%09%09Map%3CRe
@@ -3768,24 +3768,24 @@
 tSubject();%0A
-
 %09%09%09if (subj.
@@ -3815,16 +3815,86 @@
 ntinue;%0A
+%09%09%09if (ignore.containsKey(st.getPredicate().stringValue())) continue;%0A
 %09%09%09if (!

Allow for predicates to be ignored for topic detection