package cluster;

import java.io.IOException;

import misc.IO;
import graph.APSP;
import graph.DistanceMeasure;
import graph.IGraph;
import graph.NodeWeightedTimeGraph;
import graph.WeightedTimeGraph;

public class SliceTree {

	private static void printUsage() {
		System.err.print("Usage:\n" +
						 "java -jar slicetree.jar <graph file> " + 
						 "<node weight file> <time> e <rel error>  \n" +
						 "or \n" +
						 "java -jar slicetree.jar <graph file> " + 
						 "<node weight file> <time> p <num params (multiple of 5)>  \n ");
		System.exit(1);
	}
	
	private static String partitions2nodeNames(String s,
			NodeWeightedTimeGraph ntg) {
		String res = "";
		String[] parts = s.split("\n");
		for (int i = 0; i < parts.length; i++) {
			res += parts[i].split(":")[0] + ":{";
			String[] nds = parts[i].split(":")[1].replaceAll("[{}]", "").split(", ");
			for (int j = 0; j < nds.length; j++) {
				if (j>0) res += ",";
				res += ntg.names[Integer.parseInt(nds[j])];
			}
			res += "}\n";
		}
		return res;
	}
	public static void main(String[] args) throws IOException{
	
		if (args.length != 5) printUsage();
		
//		ntg = IO.readNWGraph("/home/petko/data/seine/15_traffic/preprocessed/graphall", 
//				 "/home/petko/data/seine/15_traffic/preprocessed/nwall");
		String gfn = args[0];
		String nwfn = args[1];
		int t = Integer.parseInt(args[2]);
		
		
		NodeWeightedTimeGraph ntg = IO.readNWGraph(gfn,nwfn);
		DistanceMeasure dm = new APSP(ntg,true);
		Experiment.moveWeights(ntg, t);
		
		StopCriteria sc = new StopCriteria(-1, -1);
		if (args[3].equals("e")) {
			sc.sseFraction = Double.parseDouble(args[4]);
			sc.numSplits = ntg.getn();
		} else if (args[3].equals("p")) {
			int params = Integer.parseInt(args[4]);
			if((params % 5) != 0) {
				System.err.print("Number of parameters should be multiple of 5\n");
				printUsage();
			}
			sc.numSplits = params/5;
			sc.sseFraction = 0.0;
		} else {
			printUsage();
		}
		
		SplitTreeNode tree = TreeSplitClustering.scluster(ntg, dm, sc,true);
		String s = tree.getPartitions();
		String parts = partitions2nodeNames(s, ntg);
		
		System.out.print("Params:" + tree.numSplitDecendants()*5 + "\n" +
						 "SSE:" + tree.aggregateSSE() + "\n" +
						 parts);
		//tree.visualize();
	}
}
