package net.sf.jasperreports.engine.design;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.util.JRClassLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class JRJdk13Compiler extends JRAbstractMultiClassCompiler {
  static final Log log = LogFactory.getLog(JRJdk13Compiler.class);
  
  private static final int MODERN_COMPILER_SUCCESS = 0;
  
  static Class array$Ljava$lang$String;
  
  public String compileClasses(File[] sourceFiles, String classpath) throws JRException {
    String[] source = new String[sourceFiles.length + 2];
    for (int i = 0; i < sourceFiles.length; i++)
      source[i] = sourceFiles[i].getPath(); 
    source[sourceFiles.length] = "-classpath";
    source[sourceFiles.length + 1] = classpath;
    String errors = null;
    try {
      Class clazz = JRClassLoader.loadClassForRealName("com.sun.tools.javac.Main");
      Object compiler = clazz.newInstance();
      try {
        Method compileMethod = clazz.getMethod("compile", new Class[] { (array$Ljava$lang$String == null) ? (array$Ljava$lang$String = class$("[Ljava.lang.String;")) : array$Ljava$lang$String, PrintWriter.class });
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int result = ((Integer)compileMethod.invoke(compiler, new Object[] { source, new PrintWriter(baos) })).intValue();
        if (result != 0) {
          errors = baos.toString();
        } else if (log.isInfoEnabled() && baos.size() > 0) {
          log.info(baos.toString());
        } 
      } catch (NoSuchMethodException ex) {
        Method compileMethod = clazz.getMethod("compile", new Class[] { (array$Ljava$lang$String == null) ? (array$Ljava$lang$String = class$("[Ljava.lang.String;")) : array$Ljava$lang$String });
        int result = ((Integer)compileMethod.invoke(compiler, new Object[] { source })).intValue();
        if (result != 0)
          errors = "See error messages above."; 
      } 
    } catch (Exception e) {
      StringBuffer files = new StringBuffer();
      for (int j = 0; j < sourceFiles.length; j++) {
        files.append(sourceFiles[j].getPath());
        files.append(' ');
      } 
      throw new JRException("Error compiling report java source files : " + files, e);
    } 
    return errors;
  }
}
