package j3deditor.bin.hierarchy.util;


import j3deditor.bin.hierarchy.J3DeScene;

import j3deditor.bin.util.Utilities;

import com.sun.j3d.utils.scenegraph.io.SceneGraphStreamWriter;

import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.media.j3d.BranchGroup;


/**
 * Tool for exporting scenes with
 * <code>com.sun.j3d.utils.scenegraph.io.SceneGraphStreamWriter</code>.
 *
 * @author Risto Seene
 * 
 * @see com.sun.j3d.utils.scenegraph.io.SceneGraphStreamWriter
 */
public class SGSExporter extends HierarchyWorker{

	/** scene that will be exported */
	private J3DeScene scene;

	/** path of the file the scene will be exported to */
	private String filePath;


	/**
	 * Creates an instance of <code>SGSExporter</code>
	 * which is able to export the content of the given scene.
	 *
	 * @param scene
	 *	an instance of <code>J3DeScene</code>
	 *	this exporter can export from
	 */
	public SGSExporter(J3DeScene scene){
		this.scene = scene;
	}


	/**
	 * Exports the scene to the given file.
	 *
	 * @param filePath
	 *	the path of the file the scene will be exported to
	 */
	public void exportFile(String filePath){
		this.filePath = filePath;
		this.execute();
	}
	
	
	/**
	 * Performs the exporting process in a background thread.
	 * 
	 * @return nothing
	 * @throws Exception
	 * 	if an error occurs
	 */
	protected Void doInBackground() throws Exception{
	          try{
	                    BranchGroup branchGroup = scene.getBranchGroup();
	                    buildScene(branchGroup);
	          } catch(Throwable t){
			Utilities.out.throwError(t);
	          }
		
		return null;
	}


	/**
	 * Writes the given <code>BranchGroup</code> to specified file
	 * with <code>SceneGraphStreamWriter</code>
	 *
	 * @param branchGroup
	 *	<code>BranchGroup</code> that will be written to file
	 */
	private void buildScene(BranchGroup branchGroup){
		OutputStream out = null;
		SceneGraphStreamWriter sgsWriter = null;
		try{
			out = new FileOutputStream(filePath);
			sgsWriter = new SceneGraphStreamWriter(out);

			sgsWriter.writeBranchGraph(branchGroup, null);
			sgsWriter.close();
			out.close();
		} catch(Throwable t){
			Utilities.out.throwError(t);
			try{
				out.close();
				sgsWriter.close();
			} catch(Throwable t1){
			}
		}
	}

}
