package org.etsi.t3d.visitor.tool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;

public class VisitorGenerator {

	public VisitorGenerator() {

		try {
			StringTemplateGroup group = new StringTemplateGroup("visitorGroup",
					"templates");
			group.setRefreshInterval(0); // no caching
			group.setRefreshInterval(Integer.MAX_VALUE); // no refreshing
			StringTemplate classTemplate = group
					.getInstanceOf("AbstractVisitor");
			Class<?> c = Class
					.forName("de.ugoe.cs.swe.trex.core.analyzer.rfparser.TTCN3ParserTokenTypes");
			Field[] fields = c.getFields();

			for (int i = 0; i < fields.length; i++) {
				if (!isOmitField(fields[i])) {
					classTemplate.setAttribute("nodeType", fields[i].getName());
				}
			}
			File f = new File(
					"src/org/etsi/t3d/visitor/AbstractVisitor.java");
			saveFile(f, classTemplate.toString());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// ----------------------------------------------------------------------

	private boolean isOmitField(Field f) {
		if (f.getName().contains("EOF")
				|| f.getName().contains("NULL_TREE_LOOKAHEAD"))
			return true;
		return false;
	}

	// ----------------------------------------------------------------------

	public void saveFile(File filename, String content) {
		FileOutputStream fs;
		try {
			fs = new FileOutputStream(filename);
			fs.write(content.getBytes());
			fs.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// ----------------------------------------------------------------------

	public static void main(String[] args) {
		new VisitorGenerator();
	}

}
