package de.dhbwstuttgart.parser;

import de.dhbwstuttgart.parser.SyntaxTreeGenerator.SyntaxTreeGenerator;
import de.dhbwstuttgart.parser.antlr.Java8Lexer;
import de.dhbwstuttgart.parser.antlr.Java8Parser;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.typecheck.JavaClassRegistry;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JavaTXParser {
    public SourceFile parse(File sourceFile) throws IOException, ClassNotFoundException {
        InputStream stream = new FileInputStream(sourceFile);
        ANTLRInputStream input = new ANTLRInputStream(stream);
        Java8Lexer lexer = new Java8Lexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        Java8Parser parser = new Java8Parser(tokens);
        Java8Parser.CompilationUnitContext tree = parser.compilationUnit();

        SyntaxTreeGenerator generator = new SyntaxTreeGenerator(new JavaClassRegistry(generateJavaLangNames()));
        return generator.convert(tree);
    }

    private List<String> generateJavaLangNames() throws IOException, ClassNotFoundException {
        List<String> ret = new ArrayList<>();

        for(Class cl : PackageCrawler.getClassesInPackage("java.lang")){
            ret.add(cl.getName());
        }
        //TODO: Wieso muss man das händisch anhängen?
        ret.add("java.lang.Object");
        return ret;
    }
}
