//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010 huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE----------------------------
package org.huihoo.god4j.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;

import javax.swing.JFileChooser;

import org.huihoo.god4j.GOD4JFactory;
import org.huihoo.god4j.util.ToolUtils;
import org.huihoo.workflow.impl.xpdl.serializer.DefaultXPDLSerializer;
import org.huihoo.workflow.xpdl.WorkflowPackage;

/**
 * @author liangce
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class Save extends ActionBase
{

	public Save()
	{
		super();
		setEnabled(false);
	}

	public void actionPerformed(ActionEvent e)
	{
		saveDocumentIfPossible();
	}

	public static  boolean saveDocumentIfPossible()
	{
		WorkflowPackage workflowPackage = GOD4JFactory.getGOD4J().getDocument();
		if (!ToolUtils.validateWorkflowPackage(workflowPackage))
		{
			return false;
		}

		File saveToFile = null;
		if (GOD4JFactory.getGOD4J().getFileName() == null)
		{
			JFileChooser chooser = new JFileChooser(GOD4JFactory.getGOD4J().getWorkingDirectory());
			chooser.rescanCurrentDirectory();
			if (chooser.showSaveDialog(GOD4JFactory.getGOD4J()) == JFileChooser.APPROVE_OPTION)
			{
				saveToFile = chooser.getSelectedFile();
				GOD4JFactory.getGOD4J().setFileName(saveToFile.getAbsolutePath());
				GOD4JFactory.getGOD4J().setWorkingDirectory(saveToFile.getParentFile());
			}
		}
		else
		{
			saveToFile = new File(GOD4JFactory.getGOD4J().getFileName());
		}

		if (saveToFile != null)
		{
			FileOutputStream out = null;
			try
			{
				out = new FileOutputStream(saveToFile);
				DefaultXPDLSerializer serializer = new DefaultXPDLSerializer();
				serializer.serialize(workflowPackage, out);
				
				GOD4JFactory.getGOD4J().setDirty(false);
				return true;
			}
			catch (Exception e)
			{
				return false;
			}
		}

		return false;
	}
}
