//----------------------------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.FileInputStream;

import javax.swing.JFileChooser;

import org.huihoo.god4j.GOD4JFactory;
import org.huihoo.workflow.factory.XPDLParserFactory;
import org.huihoo.workflow.impl.xpdl.parser.XPDLParserFactoryImpl;
import org.huihoo.workflow.xpdl.WorkflowPackage;
import org.huihoo.workflow.xpdl.parser.XPDLParser;

/**
 * @author liangce
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class Open extends ActionBase
{
	public Open()
	{
		super();
		setEnabled(true);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if(Close.closeDocumentIfPossible())
		{
			openDocumentIfPossible();
		}	
	}
	
	public static  boolean openDocumentIfPossible()
	{
		JFileChooser chooser = new JFileChooser(GOD4JFactory.getGOD4J().getWorkingDirectory());
		chooser.rescanCurrentDirectory();
		if (chooser.showOpenDialog(GOD4JFactory.getGOD4J()) == JFileChooser.APPROVE_OPTION)
		{
			return openDocumentIfPossible(chooser.getSelectedFile());
		}
				
		return false;
	}
	
	public static  boolean openDocumentIfPossible(String filename)
	{	
		return openDocumentIfPossible(new File(filename));
	}
	public static  boolean openDocumentIfPossible(File file)
	{
		FileInputStream in = null;
		try
		{
			in = new FileInputStream(file);
			XPDLParserFactory xpdlFactory = new XPDLParserFactoryImpl();
			XPDLParser parser = xpdlFactory.newXPDLParser();
			WorkflowPackage workflowPackage = parser.parse(in);

			GOD4JFactory.getGOD4J().setFileName(file.getAbsolutePath());
			GOD4JFactory.getGOD4J().setWorkingDirectory(file.getParentFile());
			
			GOD4JFactory.getGOD4J().loadDocument(workflowPackage);
			GOD4JFactory.getGOD4J().addToRecentFiles(file.getAbsolutePath());
			
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}
}
