// File: ActionSaveAsBeh.java
// Classes: ActionSaveAsBeh
// Author: Kedar Patankar
// Last modified : 2 March 1998
package EDU.neu.ccs.demeter.tools.apstudio.graphedit;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.awt.FileDialog;

import com.sun.java.swing.tree.DefaultMutableTreeNode;

//Action that takes defaultmutabletreenode which holds current behaviornode 
//and saves it to file on the disk. If the behavior is still carrying default name given by system then get file
//name from user or just save it.

public class ActionSaveAsBeh extends Action
{
	private DefaultMutableTreeNode _behaviorNode;

	public ActionSaveAsBeh(Editor editor,DefaultMutableTreeNode node) {super(editor);_behaviorNode= node;}
	public String name() { return "Save Strategy graphs to behavior file"; }

	public void doIt() 
	{
		BehaviorNode _behavior = (BehaviorNode)_behaviorNode.getUserObject();

// Check if all the strategy graphs in the behavior file can be stored.

		String firstName=_behavior.getName();
		if(firstName==null) 
			return; // impossible situation
		
		String filename=firstName;

		_editor.setMessage("System will add extension .str to filename if not provided by user.");
		FileDialog fd = new FileDialog(_editor, "Enter Output File Name", FileDialog.SAVE );
		fd.setDirectory(_editor.getWriteDir());
		fd.setFile(firstName);
		fd.setVisible(true);
		filename = fd.getFile();
		_editor.setDefaultMessage();  // restore the message bar status

		if (filename == null) {return;}
		filename=fd.getDirectory()+filename;
		_editor.setWriteDir(fd.getDirectory()); // remembers the last accessed folder

// Windows bug. It appends this string to filename if extension is not provided
		int a = filename.lastIndexOf(".*.*");
		if (a>0)
			filename = filename.substring(0,a);
	  	  
// Checking the extension. If user hasn't given any system will add ".str" to it.
// If user just entered "." 
		int b = filename.lastIndexOf(".");
		if(b>0)
		{
			if(b==filename.length()-1)
			{
				filename = filename.substring(0,b);				
				filename += ".str";
			}
		}
		else
			filename +=".str";
// Checking a cd file of this name is already open in the application
			if(_editor.isBehaviorAlreadyOpen(filename))
			{
				String title = "Error";
				String message = "APStudio cannot give adocument the same name as an open document";
				ActionShowMessage asm= new ActionShowMessage(_editor,title,message);
				asm.doIt();
				return;
			}
// Checking if file already exists on the disk
		boolean problem = false;
		if(new File(filename).exists())
			problem=true;
			
		if(problem) // filename already exists
		{
			String title = "File Overwrite ?";
			String message1="File already exists. Do you want to overwrite?";
			String message2=filename;
			String buttonString="YN";
			AlarmDialog ad = new AlarmDialog(_editor,title,message1,message2,buttonString,"N");
			ad.setVisible(true);
			if(ad.getChoice().equals("YES"))
			{
				if(saveThisFile(filename))
				{
					_behavior.isFirstTime(false);
					_behavior.updateName(firstName,filename);
					_editor.justSavedBehavior(firstName,filename);
				}
			}
		}
		else // filename doesn't exist its unique
		{
			if(saveThisFile(filename))
			{
				_behavior.isFirstTime(false);
				_behavior.updateName(firstName,filename);
				_editor.justSavedBehavior(firstName,filename);
			}
		}
	}

	private boolean saveThisFile(String filename)
	{
		if (filename == null)
		{
			System.out.println("no file name passed");
			return false;
		}
		BehaviorNode _behavior = (BehaviorNode)_behaviorNode.getUserObject();

// Checking if it can be saved

		String strString = _behavior.getString(_behaviorNode);// Obtained the total string for behaviornode
		if(strString == null)
		{
			String title = "Error : Can not save the behavior";
			String message = "There must be at least one strategy graph having at least one incomplete or no strategy edge";
			ActionShowMessage asm= new ActionShowMessage(_editor,title,message);
			asm.doIt();
			return false;
		}

		_editor.setMessage("Saving file "+filename);
		FileOutputStream str;
		try
		{
			str = new FileOutputStream(filename);
		}catch(IOException eb){return false;}

		if(saveStringToDisk(str,strString))
		{
			_editor.setMessage(filename +" saved");
			_behavior.needsSaving(false);
			return true;
		}
		_editor.setMessage("Error saving file");
		return false;
	}

	private boolean saveStringToDisk(FileOutputStream out,String graphString)
	{
		if (graphString == null)
			graphString = "";
		byte[] buf = new byte[graphString.length()];
		buf = graphString.getBytes();
		try
		{
			out.write(buf);
			out.close();
		}catch (IOException eb){return false;}
		return true;
	}


	public void undoIt() { }

} /* end class ActionSaveAsBeh */

