package bytecode;

import static org.junit.Assert.*;

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

import org.junit.BeforeClass;
import org.junit.Test;

import de.dhbwstuttgart.core.JavaTXCompiler;

public class FieldTphMMethTest {

	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;
	private static Object instanceOfClass2;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		path = System.getProperty("user.dir")+"/src/test/resources/bytecode/javFiles/FieldTphMMeth.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("FieldTphMMeth");
		instanceOfClass = classToTest.getConstructor(Object.class,Object.class,Boolean.class).newInstance("C",42,true);
		instanceOfClass2 = classToTest.getConstructor(Object.class,Object.class,Boolean.class).newInstance("C",42,false);
	}

	@Test
	public void testM() throws Exception {
		
		Method m = classToTest.getDeclaredMethod("m", Object.class,Object.class,Boolean.class);
		Object result = m.invoke(instanceOfClass, "C",42,false);
		
		assertEquals(42,result);
	}
	
	@Test
	public void testWithTrue() throws Exception {
		Field a = classToTest.getDeclaredField("a");
		a.setAccessible(true);

		assertEquals("C", a.get(instanceOfClass));
		
	}
	
	@Test
	public void testWithFalse() throws Exception {
		Field a = classToTest.getDeclaredField("a");
		a.setAccessible(true);
		
		assertEquals(42, a.get(instanceOfClass2));
	}

}
