package de.dhbwstuttgart.strucTypes;

import java.util.List;

import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.Field;
import de.dhbwstuttgart.syntaxtree.FormalParameter;
import de.dhbwstuttgart.syntaxtree.Method;
import de.dhbwstuttgart.syntaxtree.SourceFile;

public class CodeGenerator {
	
	
	public static String generate(SourceFile sf, List<AS_Abstract> ass) {
		String code = ""; 		
		
		// Generate Classes
		for (ClassOrInterface cl : sf.getClasses()) {
			String code_class = generateClass(cl,ass); 
			code = code +  code_class; 			
		}		
		return code; 
	}
	
	
	
	
	public static String generateClass(ClassOrInterface cl, List<AS_Abstract> ass ) {
		String code = "class " + cl.getClassName() + " {  \n \n"; 
		
		// Felder 
		for (Field f :  cl.getFieldDecl()) {
			String code_field = AS_Abstract.find_AS_Field(f, ass).get_code(); 
			code = code + code_field + " \n"; 			
		}
		
		code = code + "\n \n"; 
		
		
		// Methoden
		for (Method m : cl.getMethods() ) {
			String m_string = generateMethod(m, ass); 
			code = code + m_string +  "\n \n"; 			
		}		
		return code + "\n } "; 		
	}
		
	
	
	
	public static String generateField(SourceFile sf, List<AS_Abstract> ass ) {
		String code = ""; 
				
		return code; 
	}
	
	
	
	public static String generateMethod(Method m, List<AS_Abstract> ass ) {
		
		String rt_type = Algo_TypeExpr.get_Return_typed(m, ass); 		
		
		
		String code = rt_type +" "  +  m.getName() + "  (  " ; 
		
		// Generate Formalparameter
		List<FormalParameter> fp = m.getParameterList().getFormalparalist(); 
		for (FormalParameter f : fp ) {
			//AS_Argument arg = AS_Abstract.find_AS_Argument(f, ass); 
			AS_Argument arg = AS_Abstract.find_AS_Argument(f, m, ass); 
			code = code + arg.get_code() + ", "; 
		}
		
		if (fp.size() > 0) {
			code = code.substring(0, code.length() -2); 
		}
		
		String expression_str = Algo_TypeExpr.expression2code(ass ,m.get_Block().statements);
		code = code + String.format(" )  { \n  return %s   } " , expression_str); 
			
		return code; 
	}
	
	
	
	
	
	
	
	
	
	
	

}
