import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.util.Arrays;

import javax.tools.*;
import javax.tools.JavaCompiler.*;


public class RunTranslation {
	public static void main(String args[]){
		if(args.length == 0) {
			System.out.println("name of model required as argument");
			return;
		}
		
		compileModel(args[0]);
	}
	
	public static void compileModel(String name){
		String className = name;
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

		StringWriter writer = new StringWriter();
		PrintWriter out = new PrintWriter(writer);
		out.println(getClipboardCode());
		out.close();
		JavaFileObject file = new JavaSourceFromString(className, writer.toString());

		Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
		CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

		boolean success = task.call();
		if(!success){
			System.out.println("Error Building Model");
			return;
		}
		/*try {
			Class.forName(className).getDeclaredMethod("evaluate", new Class[]{LiveEdit.class}).invoke(null, new Object[]{cls});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		File classFile = new File(System.getProperty("java.class.path") + "/" + className + ".class");
		classFile.delete();*/
	}
	
	private static String getClipboardCode(){
		try {
			return (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
}
class JavaSourceFromString extends SimpleJavaFileObject {
	final String code;

	JavaSourceFromString(String name, String code) {
		super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
		this.code = code;
	}

	@Override
	public CharSequence getCharContent(boolean ignoreEncodingErrors) {
		return code;
	}
}
