package im.saito.dot;


import im.saito.statemachine.State;
import im.saito.statemachine.Transition;
import im.saito.example.Process;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;


public class Helper {

	static final String	template	= "digraph finite_state_machine {\n" + "\trankdir=LR;\n" + "\tsize=\"8,5\"\n"
											+ "\tnode [shape = doublecircle];\n\n";
	static final String	close		= "}";

	public static void main(String args[]) {
		// file name
		File dot = new File("src/im/saito/dot/fsm.dot");
		// dot context
		String content = ctx(new Process().states);

		try {
			if (!dot.exists())
				dot.createNewFile();
			BufferedWriter output = new BufferedWriter(new FileWriter(dot));
			output.write(template);
			output.write(content);
			output.write(close);
			output.flush();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static String ctx(Map<String, State> map) {

		StringBuilder appender = new StringBuilder();

		for (State state : map.values()) {
			for (Transition transition : state.nexts) {
				appender.append("\t");
				appender.append(state.name + " -> " + transition.to);
				if (transition.exp != null)
					appender.append(" [ label = \"" + transition.exp + "\" ]");
				appender.append(";\n");
			}
		}

		return appender.toString();
	}

}

@@ -541,19 +541,17 @@
 %0A%09%09File 
-dot
+f
  = new F
@@ -663,19 +663,17 @@
 %09%09%09if (!
-dot
+f
 .exists(
@@ -679,19 +679,17 @@
 ())%0A%09%09%09%09
-dot
+f
 .createN
@@ -759,19 +759,17 @@
 eWriter(
-dot
+f
 ));%0A%09%09%09o
@@ -934,16 +934,29 @@
 e();%0A%09%09%7D
+%0A%09%09%0A%09%09dot(f);
 %0A%0A%09%7D%0A%0A%09p
@@ -1360,16 +1360,16 @@
 %09%7D%0A%09%09%7D%0A%0A
-
 %09%09return
@@ -1392,12 +1392,299 @@
 ng();%0A%09%7D
+%0A%09%0A%09private static void dot(File f)%7B%0A%09%09String abpath = f.getAbsolutePath();%0A%09%09String cmd = %22dot -Tpng %22+abpath+%22 -o%22+f.getAbsolutePath()+%22.png%22;%0A%09%09ProcessBuilder pb = new ProcessBuilder(%22bash%22, %22-c%22, cmd);%0A%09%09try %7B%0A%09%09%09pb.start();%0A%09%09%7D catch (IOException e) %7B%0A%09%09%09e.printStackTrace();%0A%09%09%7D%0A%09%7D
 %0A%0A%7D%0A

add dot support in helper