package bytecode;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import org.junit.Test;

import de.dhbwstuttgart.core.JavaTXCompiler;

public class FacultyTest {
	private static String path;
	private static File fileToTest;
	private static JavaTXCompiler compiler;
	private static ClassLoader loader;
	private static Class<?> classToTest;
	private static String pathToClassFile;
	private static Object instanceOfClass;
	
	@Test
	public void generateBC() throws Exception {
		path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/Faculty.jav";
		fileToTest = new File(path);
		compiler = new JavaTXCompiler(fileToTest);
		compiler.generateBytecode(System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/");
		pathToClassFile = System.getProperty("user.dir")+"/src/test/resources/testBytecode/generatedBC/";
		loader = new URLClassLoader(new URL[] {new URL("file://"+pathToClassFile)});
		classToTest = loader.loadClass("Faculty");
		instanceOfClass = classToTest.getDeclaredConstructor().newInstance();
		
		Method getFact = classToTest.getDeclaredMethod("getFact", Integer.class);
//		Field fact = classToTest.getDeclaredField("fact");
//		Class<?> lambda = m.invoke(instanceOfClass).getClass();
//		Class<?> lambda = fact.getType();
//		System.out.println(fact.getType().getName());
//		Method apply = lambda.getMethod("apply", Object.class);
//		System.out.println(lambda.getMethods()[0]);
//		System.out.println(instanceOfClass.toString());
//		// Damit man auf die Methode zugreifen kann
//		apply.setAccessible(true);
		// Field value
//		Object fieldVal = fact.get(instanceOfClass);
		Integer i = 3;
//		Method applyFromField = fieldVal.getClass().getDeclaredMethod("apply", Object.class);
//		applyFromField.setAccessible(true);
//		Integer result = (Integer) apply.invoke(lambda,i);
		Integer result = (Integer) getFact.invoke(instanceOfClass,i);

		assertEquals(new Integer(6), result);
	}


}
