package net.sf.jasperreports.engine.design;

import java.io.File;
import java.io.Serializable;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.util.JRLoader;

public abstract class JRAbstractClassCompiler extends JRAbstractJavaCompiler implements JRMultiClassCompiler {
  protected JRAbstractClassCompiler() {
    super(true);
  }
  
  protected String compileUnits(JRCompilationUnit[] units, String classpath, File tempDirFile) throws JRException {
    File[] sources = new File[units.length];
    for (int i = 0; i < sources.length; i++)
      sources[i] = units[i].getSourceFile(); 
    File[] classFiles = new File[units.length];
    for (int j = 0; j < classFiles.length; j++)
      classFiles[j] = new File(tempDirFile, units[j].getName() + ".class"); 
    try {
      String errors = compileClasses(sources, classpath);
      if (errors == null)
        for (int m = 0; m < units.length; m++) {
          byte[] classBytes = JRLoader.loadBytes(classFiles[m]);
          units[m].setCompileData((Serializable)classBytes);
        }  
      return errors;
    } finally {
      for (int k = 0; k < classFiles.length; k++) {
        if (classFiles[k].exists())
          classFiles[k].delete(); 
      } 
    } 
  }
  
  protected void checkLanguage(String language) throws JRException {
    if (!"java".equals(language))
      throw new JRException("Language \"" + language + "\" not supported by this report compiler.\n" + "Expecting \"java\" instead."); 
  }
  
  protected JRCompilationSourceCode generateSourceCode(JRSourceCompileTask sourceTask) throws JRException {
    return JRClassGenerator.generateClass(sourceTask);
  }
  
  protected String getSourceFileName(String unitName) {
    return unitName + ".java";
  }
}
