// File: GraphViewer.java
// Copyright (C) 2006 Gregory D. Weber

import java.io.*; // for FileWriter, IOException, InputStreamReader

public class GraphViewer {

    public static void view (Graphable obj) {

	// Ask the object for its DOT language representation
	String dotRepr = obj.toDot();

	// System.err.println("DEBUG: have dot string:");
	// System.err.println(dotRepr);

	// Write it to a file
	try {
	    FileWriter dotfile = new FileWriter("tmp.dot");
	    dotfile.write(dotRepr);
	    dotfile.close();
	    // System.err.println("Wrote dot file: tmp.dot");

	    // Display the file
	    ProcessBuilder pb1 =
 		new ProcessBuilder("/usr/bin/dot", "-Tpng", 
				   "-otmp.png", "tmp.dot");
						   
	    boolean okay = run(pb1);
	    // System.err.println("Ran dot; result = " + okay);

	    if (okay) {
		ProcessBuilder pb2 =
		    new ProcessBuilder(// "/usr/bin/display",  
				       "/usr/bin/feh",
				       "tmp.png");
		okay = run(pb2);
		// System.err.println("Ran display; result = " + okay);
	    }
	}

	catch (IOException e) {
	    // System.err.println("GraphViewer.view: I/O error.");
	}
	// We won't clean up the file	
    }

    private static boolean run (ProcessBuilder pb) {
	pb.redirectErrorStream(true);
	try {
	    Process p1 = pb.start();
	    InputStreamReader pin = 
		new InputStreamReader(p1.getInputStream());
	    int chr = pin.read();
	    // System.err.println("SUBPROCESS OUTPUT:");
	    while (chr != -1) {
		System.out.write(chr);
		chr = pin.read();
	    }
	    pin.close();
	    // System.err.println("END");
	    try {
		int retcode = p1.waitFor();
		if (retcode != 0)
		    System.out.println("Subprocess return code: " + retcode);
		// System.err.println("Subprocess returned " + retcode);
		return (retcode == 0);
	    }
	    catch (InterruptedException e) {
		System.err.println("Interrupted!");
		return false;
	    }
	}
	catch (IOException e) {
	    System.err.println("I/O exception.");
	    return false;
	}
    }

}

	
