// File: ActionSave.java
// Classes: ActionSave
// Author: Kedar Patankar

package EDU.neu.ccs.demeter.tools.apstudio.graphedit;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Hashtable;
import java.awt.FileDialog;
import java.awt.Point;
import java.awt.Dialog;
import EDU.neu.ccs.demeter.Ident;

/**
 * Action to take the graph structure and write it to a file selected by user */

public class ActionSave extends Action
{
	private boolean _userCancelled;
	
	public ActionSave(Editor editor,Document d) {super(editor,d); }
	public String name() { return "Save Graph Structure"; }

	public boolean executeIt()
	{
		_userCancelled=false;
		doIt();
		return !_userCancelled;
	}

	public void doIt() 
	{
		String firstName=_document.getDocName();
		if(firstName==null) 
		{
			_userCancelled=true;
			return; // impossible situation
		}
		
		String filename=firstName; // This name will be used if this is not the first time.
		
		if (_document.firstTime())
		{
			_editor.setMessage("System will add extension .cd 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();
			_document.mode().setMessage(_editor);

			if (filename == null) {_userCancelled=true;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 ".cd" to it.
			int b = filename.lastIndexOf(".");
			if(b>0)
			{
				if(b==filename.length()-1)
				{
					filename = filename.substring(0,b);				
					filename += ".cd";
				}
			}
			else
				filename +=".cd";
// Checking a cd file of this name is already open in the application
			if(_editor.isPresent(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();
				_userCancelled = true;
				return;
			}

// Checking if filename is already used
			boolean problem = false;
			if(new File(filename).exists())
				problem=true;
			
			if(problem)
			{
				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))
					{
						_document.firstTime(false);
						_editor.updateDocname(firstName,filename);
					}
					else
						_userCancelled = true;
				}
			}
			else
			{
				_document.cdNeedsSaving(true); // since this is first time, u got to save the cd as well gcd
				if(saveThisFile(filename))
				{
					_document.firstTime(false);
					_editor.updateDocname(firstName,filename);
				}
				else
					_userCancelled = true;
			}
		}
		else
		{
			if(!saveThisFile(filename))
				_userCancelled = true;
		}
	}

	private boolean saveThisFile(String filename)
	{
		if (filename == null)
		{
			System.out.println("no file name passed");
			return false;
		}

		UGraph graph = _document.toExactGraph();
		
		if(graph==null)
		{
			System.out.println("graph is null");
			return false;
		}
		
		if(_document.cdNeedsSaving())
		{
			String cdFile = filename;
			
			if (!_document.firstTimeCreated())
				cdFile += ".apcd";

			String gcdFile = filename + ".gcd";
			FileOutputStream cd,gcd;
			try
			{
				cd = new FileOutputStream(cdFile);
				gcd = new FileOutputStream(gcdFile);
			}catch(IOException eb){return false;}

			String gcdString,cdString;
			try
			{
				gcdString = gcdToString(graph);
				cdString = cdToString(graph);
			}
			catch(java.lang.Throwable ex)
			{
				_editor.setMessage("Error saving file");
				return false;
			}

			_editor.setMessage("Saving file "+cdFile);
			if(saveStringToDisk(cd,cdString) && saveStringToDisk(gcd,gcdString))
			{
				_editor.setMessage(cdFile+" saved");
				_document.cdNeedsSaving(false);
				return true;
			}
			_editor.setMessage("Error saving file");
			return false;
		}
		else
		{
			String gcdFile = filename + ".gcd";
			FileOutputStream gcd;
			try
			{
				gcd = new FileOutputStream(gcdFile);
			}catch(IOException eb){return false;}

			String gcdString = gcdToString(graph);
			if(gcdString==null)
				return false;

			_editor.setMessage("Saving file "+ filename);
			if(saveStringToDisk(gcd,gcdString))
			{
				_editor.setMessage(filename+" saved");
				_document.gcdNeedsSaving(false);
				return true;
			}
			_editor.setMessage("Error saving file");
			return false;
		}
	}
  
	private String cdToString(UGraph graph)
	{
		String graphString=graph.getCdString();
		return graphString;
	}

	private String gcdToString(UGraph graph)
	{
		String graphString=graph.GetGraphString();
		return graphString;
	}

	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 ActionSave */

