package de.visone.nlpext.deprecated;

import java.io.File;
import java.util.Arrays;

import org.apache.log4j.Logger;

import de.visone.base.Network;
import de.visone.nlpext.deprecated.CentralityUtil.Centrality;
import de.visone.nlpext.util.GraphMLFileFilter;
import de.visone.nlpext.util.HeadlessMediator;

/**
 * @author <a href="mailto:endele@inf.uni-konstanz.de">Simon Endele</a>
 */
public class CentralityComputer {
	private static final Logger logger = Logger
			.getLogger(CentralityComputer.class);
	private static final String DEFAULT_CENTRALITY = "betweenness";

	/**
	 * Calculates either degree- or betweeneness-centrality of all networks in
	 * the directory specified by args[0] and saves them as .
	 */
	public static void main(final String[] args) throws Exception {
		final HeadlessMediator mediator = new HeadlessMediator();
		if (args == null || args.length != 2) {
			logger.info("Usage is: java CentralityComputer <networkDir> <centralityName>");
			return;
		}
		final String networkDir = args[0];
		final String centralityName = args[1];
		if (!new File(networkDir).exists()) {
			logger.info("Dir does not exist: " + networkDir);
			return;
		}

		// AttributeInterface<Node> uniNodeMap = UniformWeightMapFactory
		// .getUniformNodeMap();
		// AttributeInterface<Edge> uniEdgeMap = UniformWeightMapFactory
		// .getUniformEdgeMap();
		Centrality centrality = CentralityUtil.getNodeCentrality(
				centralityName, null, null);
		final Centrality ecentrality = CentralityUtil.getEdgeCentrality(
				centralityName, null, null);
		if (centrality == null) {
			logger.warn("no centrality named " + centralityName + ", using "
					+ DEFAULT_CENTRALITY);
			centrality = CentralityUtil.getNodeCentrality(DEFAULT_CENTRALITY,
					null, null);
		}

		final File[] networkFiles = new File(networkDir)
				.listFiles(new GraphMLFileFilter());
		Arrays.sort(networkFiles);
		for (final File networkFile : networkFiles) {
			logger.info("Loading network from " + networkFile.getAbsolutePath()
					+ "...");
			final Network network = NetworkUtil.loadNetwork(networkFile);

			logger.info("Calculating centrality...");
			centrality.runAlgorithm(centralityName, network);
			ecentrality.runAlgorithm(centralityName, network);

			final String fileName = networkFile.getAbsolutePath();
			final File attributeFile = new File(fileName.substring(0,
					fileName.lastIndexOf('.'))
					+ "_" + centralityName + ".csv");
			NetworkUtil.saveAttributes(network, attributeFile);
			logger.info("Saved attributes to " + attributeFile);
			mediator.disposeNetwork(network);
		}

		// NodeMap wordMap = TextNetwork.getWordMap(network);
		// AttributeInterface<Node> betweenness =
		// NetworkUtil.loadAttribute(network, csvFilename, "Betweenness");
	}
}
