package xyz.ignatz.antlr.java9;

import guru.nidi.graphviz.engine.Format;
import guru.nidi.graphviz.engine.Graphviz;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import xyz.ignatz.antlr.java9.recognizer.Java9Lexer;
import xyz.ignatz.antlr.java9.recognizer.Java9FlowchartVisitor;
import xyz.ignatz.antlr.java9.recognizer.Java9Parser;
import xyz.ignatz.flowchart.Flowchart;

import java.io.File;
import java.io.IOException;
import java.util.Formatter;
import java.util.List;

public class Java9FlowchartGenerator {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("JavaControlFlowGenerator input_filename output_directory");
            return;
        }
        String inputFileName = args[0];
        String outputDirectory = args[1];
        CharStream input = null;
        try {
            input = CharStreams.fromFileName(inputFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] lines = input.toString().split("\n|\r\n|\n\r");
        for (int i=0; i<lines.length; ++i) {
            Formatter formatter = new Formatter();
            System.out.println(formatter.format("%4d. %s\n", i+1, lines[i]));
        }
        Java9Lexer lexer = new Java9Lexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        Java9Parser parser = new Java9Parser(tokens);
        ParseTree tree = parser.compilationUnit();
        Java9FlowchartVisitor visitor = new Java9FlowchartVisitor();
        visitor.visit(tree);
        List<Flowchart> flowcharts = visitor.getFlowcharts();
        for (Flowchart flowchart : flowcharts) {
            String outputFileName = outputDirectory + '/' + flowchart.getName();
            File file = new File(outputFileName);
            try {
                Graphviz.fromGraph(flowchart.graph()).render(Format.SVG).toFile(file);
            } catch (IOException e) {
                System.err.println("[ERROR] Output " + outputFileName + " error.");
                e.printStackTrace();
            }
        }
    }
}
