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.typecheck.JavaClassName;
import de.dhbwstuttgart.typecheck.JavaClassRegistry;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import de.dhbwstuttgart.syntaxtree.*;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class RunParser{
  public static void main(String[] args){
    try{
      File file = new File(args[0]);
      Scanner sc = new Scanner(file);
      String inputString = sc.nextLine();
      while(sc.hasNextLine()) inputString = inputString + sc.nextLine() + "\n";
      InputStream stream = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
      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(new ArrayList<>()));
      generator.setImports(tree);
      SourceFile f = generator.convert((Java8Parser.CompilationUnitContext) tree);
      String pkgName = f.getPkgName();
      System.out.println("package: " + pkgName);
      System.out.println("Imports:");
      for(JavaClassName c : f.getImports()){
        System.out.println(c.toString());
      }
      System.out.println("classes:");
      for(ClassOrInterface c : f.getClasses()){
        int mod = c.getModifiers();
        System.out.println(Modifier.toString(mod));
        System.out.println(c.getClassName().toString());
        System.out.println("{");
        for(Field field : c.getFieldDecl()){
          System.out.println(field.getName());
        }
        System.out.println("}");
      }
    }
    catch(java.util.NoSuchElementException e){
      System.out.println("Error: Source seems to be empty.");
    }
    catch(FileNotFoundException e){
      System.out.println("File not found.");
    }
    catch(InvalidClassNameException e){
      e.printStackTrace();
    }
    catch(IOException e){
      System.out.println("An exception occured which is on our TODO list.");
      e.printStackTrace();
    }
  }
}
