import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import org.apache.log4j.Logger;

import de.visone.base.Network;
import de.visone.nlpext.gui.CRACard;
import de.visone.nlpext.gui.NLPPanel;
import de.visone.nlpext.gui.WNACard;
import de.visone.nlpext.network.TextNetwork;
import de.visone.nlpext.util.HeadlessMediator;

/**
 * Simple tool to batch-create text networks.
 * 
 * @author matthias
 */
public class Batch {
	private static Logger logger = Logger.getLogger(Batch.class);

	private Batch() {
	}

	protected static void usage() {
		System.err.println("usage: java -cp visone-nlp.jar:visone.jar"
				+ " Batch algorithm input [output]");
		System.err.println("creates .graphml networks in directory output"
				+ " for all .txt files in input");
		System.err.println("if output is omited, it is the same as input");
		System.err.println("valid algoithms are 'cra' and 'wna'");
		System.err.println("stanford CoreNLP may require an additional"
				+ " -Xmx2g or similar");
		System.exit(1);
	}

	public static void main(final String... args)
			throws IllegalArgumentException, SecurityException,
			IllegalAccessException, NoSuchFieldException, IOException {
		if (args.length != 2 && args.length != 3)
			usage();
		final String algorithm = args[0];
		final String input = args[1];
		final String output;
		if (args.length == 2)
			output = input;
		else
			output = args[2];

		final HeadlessMediator mediator = new HeadlessMediator();
		final NLPPanel algo;
		if (algorithm.equalsIgnoreCase("wna"))
			algo = new WNACard(mediator);
		else if (algorithm.equalsIgnoreCase("cra"))
			algo = new CRACard(mediator);
		else {
			usage();
			return;
		}
		algo.getParameterPanel();

		final File[] textFiles = new File(input)
				.listFiles(new FilenameFilter() {
					@Override
					public boolean accept(final File dir, final String name) {
						return name.endsWith(".txt");
					}
				});
		final File outputDir = new File(output);
		for (final File textFile : textFiles) {
			try {
				logger.info("processing " + textFile.getName());
				final TextNetwork textNet = algo.getTextNetwork();
				textNet.buildNetwork(textFile);
				final Network network = textNet.getNetwork();
				final File outputFile = new File(outputDir, textFile.getName()
						.replaceFirst(".txt$", "") + ".graphml");
				mediator.getIOManager().write(outputFile,
						mediator.getBundle(network));
				logger.info("wrote " + outputFile.getName());
				mediator.disposeNetwork(network);
			} catch (final Throwable e) {
				logger.error(
						textFile.getName() + " failed with " + e.toString(), e);
			}
		}
	}
}
