package bytecode;

import de.dhbwstuttgart.bytecode.BytecodeGen;
import de.dhbwstuttgart.core.JavaTXCompiler;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static org.junit.Assert.*;

public class JavaTXCompilerTest  {

    private static final String rootDirectory = System.getProperty("user.dir")+"/test/javFiles/";
    private static final List<File> filesToTest = new ArrayList<>();

    @Test
    public void test() throws IOException, java.lang.ClassNotFoundException {
    		System.out.println(rootDirectory);
        filesToTest.add(new File(rootDirectory+"EmptyClass.jav"));
        JavaTXCompiler compiler = new JavaTXCompiler(filesToTest);
        System.out.println("test");
        for(File f : filesToTest){
            String content = readFile(f.getPath(), StandardCharsets.UTF_8);
            HashMap<String,byte[]> bytecode = this.getBytecode(compiler.sourceFiles.get(f));
            this.writeClassFile(bytecode, "EmptyClass");
        }

    }
    

    public HashMap<String,byte[]> getBytecode(SourceFile sf) {
    		HashMap<String,byte[]> classFiles = new HashMap<>();
    		BytecodeGen bytecodeGen = new BytecodeGen(classFiles);
    		bytecodeGen.visit(sf);
    		return bytecodeGen.getClassFiles();
	}
    
    public void writeClassFile(HashMap<String,byte[]> classFiles, String name) {
    		FileOutputStream output;
    		byte[] bytecode = classFiles.get(name);
		try {
			System.out.println("generating .class file");
			output = new FileOutputStream(new File(System.getProperty("user.dir") + "/testBytecode/" +name+".class"));
			output.write(bytecode);
			output.close();
			System.out.println(".class file generated");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

	static String readFile(String path, Charset encoding)
            throws IOException
    {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }

}