package j3deditor.bin.hierarchy.util;


import j3deditor.bin.hierarchy.J3DeScene;

import j3deditor.bin.util.Utilities;

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

import java.io.File;

import javax.media.j3d.BranchGroup;


/**
 * Tool for exporting scenes with
 * <code>com.sun.j3d.utils.scenegraph.io.SceneGraphFileWriter</code>.
 *
 * @author Risto Seene
 * 
 * @see com.sun.j3d.utils.scenegraph.io.SceneGraphFileWriter
 */
public class SGFExporter 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>SGFExporter</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 SGFExporter(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>SceneGraphFileWriter</code>
	 *
	 * @param branchGroup
	 *	<code>BranchGroup</code> that will be written to file
	 */
	private void buildScene(BranchGroup branchGroup){
		SceneGraphFileWriter sgfWriter = null;
		try{
			File out = new File(filePath);
			sgfWriter = new SceneGraphFileWriter(out, null, false, "", null);

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

}
