package com.horstmann.labrat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.Path;

public class SnapFrameTask extends Task
{
   public void execute() throws BuildException
   {
      try
      {
         Class serviceClass = SnapFrame.class;
         
         // we write the class file to a temporary jar so we can add it to the classpath 
         File tempJar = File.createTempFile("snap", ".jar");
         FileOutputStream fout = new FileOutputStream(tempJar);
         ZipOutputStream zout = new ZipOutputStream(fout);
         String serviceClassPath = serviceClass.getName().replace('.', '/') + ".class";
         ZipEntry ze = new ZipEntry(serviceClassPath);
         zout.putNextEntry(ze);
         InputStream in = getClass().getResourceAsStream("/" + serviceClassPath);
         int ch;
         while ((ch = in.read()) != -1)
            zout.write(ch);
         zout.closeEntry();
         zout.close();
         
         Java javaTask = new Java();
         javaTask.setClassname(serviceClass.getName());
         classpath.add(new Path(getProject(), tempJar.getAbsolutePath()));
         javaTask.setClasspath(classpath);
         javaTask.createArg().setValue(classname);
         javaTask.createArg().setValue(output);
         javaTask.setOwningTarget(getOwningTarget());
         javaTask.setProject(getProject());
         javaTask.setFork(true);
         javaTask.execute();
         
         tempJar.delete();
      }
      catch (Exception ex)
      {
         log("" + ex);
      }
   }

   public void setClassname(String classname)
   {
      this.classname = classname;
   }

   public void setClasspath(Path classpath)
   {
      this.classpath = classpath;
   }

   public void setOutput(String output)
   {
      this.output = output;
   }

   private Path classpath;
   private String classname;
   private String output;
}
