import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.event.*;

/**
* File handler handles all the request from the file menu
* extends Handler object so it can be loaded in JPE object
*/
public class FileHandler extends Handler {

	// Strings for the pulldown
	private String OpenString="Open";
	private String CloseString="Close";
	private String LockString="Lock/Unlock";
	private String SaveString="Save";
	private String SaveAsString="Save As ...";
	private String NewString="New";
	private String ExitString="Exit";

	/**
	* create the file handler
	*/
	public FileHandler(JPE jpe) {
		super(jpe);
		name="File";
	}

	/**
	*  called by superclass to create its menu
	*/
	public Menu createMenu() {
		Menu m = new Menu(name);
		m.add(new MenuItem(NewString,new MenuShortcut('N')));    
		m.add(new MenuItem(OpenString,new MenuShortcut('O')));    
		m.add(new MenuItem(CloseString,new MenuShortcut('X',true)));    
		m.add(LockString);
		m.add(new MenuItem(SaveString,new MenuShortcut('S')));    
		m.add(new MenuItem(SaveAsString,new MenuShortcut('S',true)));
		m.addSeparator();
		m.add(new MenuItem(ExitString,new MenuShortcut('E')));    
		m.addActionListener(this);        
		return(m);
	}

	/**
	*  AWT callback (implemented in Handler) for menu events
	*/
    public void actionPerformed(ActionEvent evt)	{
		String cmd = evt.getActionCommand();
		if (cmd.equals(ExitString)) {
			doExit();
		} else if (cmd.equals(OpenString)) {
			openFile();
		} else if (cmd.equals(CloseString)) {
			closeFile();
		} else if (cmd.equals(LockString)) {
			lockFile();
		} else if (cmd.equals(NewString)) {
			newFile();
		} else if (cmd.equals(SaveString)) {
			saveFile();
		} else if (cmd.equals(SaveAsString)) {
			saveAsFile();
		}
	}

	/**
	* do find uses the askInterface
	*/
	public void doExit() {
		jpe.setAskMode(this,"exit","Exit JPE (y/n) ? ",true);
	}

	/**
	* do Exit
	*/
	public void handleExit(String result) {
		if (result.equals("y")) {
			// check if all files are saved 
			OpenFileHandler ofh=(OpenFileHandler)jpe.getHandler("Opened");	
			if (ofh!=null && ofh.allFilesSaved()) {
				jpe.wantexit=true;
				jpe.say("Exit called, goodbye");
				ofh.updateProperties();
				System.exit(0);
			} else {
				jpe.say("Exit ignored because files not saved");
			}
		} else {
			jpe.say("Exit ignored");
		}
	}


	/**
	* create new file, under the name untitled or a followup
	* untitled2, untitled3 etc etc
	*/
	public void newFile() {
		// get the openfile handler to add the new file
		OpenFileHandler ofh=(OpenFileHandler)jpe.getHandler("Opened");	
		if (ofh==null) {
			// no opened handler started so lets start one and add it the
			// menu.
			ofh=(OpenFileHandler)jpe.addHandler(new OpenFileHandler(jpe));
			jpe.getMenuBar().add(ofh.createMenu());
		}


		// find a empty untitled filename
		String prefix="untitled";
		String filename=prefix;
		int i=2;
		// repeat until we found one	
		while (ofh.isLoaded(filename)) {
			filename=prefix+(i++);	
		}

		// open a file with the found name
		OpenFile file=new OpenFile(filename);

		// add the file to the opened file list
		ofh.addFile(file);

		// load this file into the text area
		jpe.getTextHandler().useFile(file);
	}

	/**
	* open a file, lets the user pick one using a FileDialog
	*/
	private void openFile()	{
		// get the openfile handler to add the new file
		OpenFileHandler ofh=(OpenFileHandler)jpe.getHandler("Opened");	
		if (ofh==null) {
			// no opened handler started so lets start one and add it the
			// menu.
			ofh=(OpenFileHandler)jpe.addHandler(new OpenFileHandler(jpe));
			jpe.getMenuBar().add(ofh.createMenu());
		}

		// open a dialog to let the user select the file we need to load	
		String filename=getFileName(FileDialog.LOAD);

		// lets check if we allready have this file open
		OpenFile file=ofh.getOpenFile(filename);
		if (file==null) {
			// file not opened at this moment lets open it		
			file=new OpenFile(filename);
			ofh.addFile(file);
		}
		
		// load this file into the text area
		jpe.getTextHandler().useFile(file);
	}

	private void lockFile() {
		OpenFileHandler ofh=(OpenFileHandler)jpe.getHandler("Opened");	
		TextHandler txth=(TextHandler)jpe.getTextHandler();	
		if (txth!=null) {
			OpenFile file=txth.getEditFile();
			if (file.isLocked()) {
				file.clearLocked();
				jpe.say("file is now unlocked ( read / write )");
			} else {
				file.setLocked();
				jpe.say("file is now locked (read only)");
			}
			jpe.setLockState(file.isLocked());
			ofh.updateProperties();
		}
	}
	/**
	* close the selected file, meaning removing it from the Opened
	* list and removing it from the auto reload on startup list
	*/
	private void closeFile() {
		OpenFileHandler ofh=(OpenFileHandler)jpe.getHandler("Opened");	
		TextHandler txth=(TextHandler)jpe.getTextHandler();	
		if (txth!=null) {
			OpenFile file=txth.getEditFile();
			if (!file.isDirty()) {
				ofh.removeFile(file);
				ofh.switchOpenFile();
			} else {
				jpe.setAskMode(this,"close","File not saved, save first  (y/n) ? ",true);
			}
		}
	}

	
	private void handleClose(String result) {
		// get the text handler 
		TextHandler txth=(TextHandler)jpe.getTextHandler();	
		if (txth!=null) {
			// get the selected file from the text handler
			OpenFile file=txth.getEditFile();
			if (file!=null) {
				if (result.equals("y")) file.saveFile();
				file.clearDirty();
				closeFile();
			}
		}
	}


	/**
	* ask the user for a filename (using a file requester) and save
	* the current file under that name
	*/
	private void saveAsFile() {
		// get openfile handlers
		OpenFileHandler ofh=(OpenFileHandler)jpe.getHandler("Opened");	
		if (ofh!=null) {
			// ask the user for the file name
			String filename=getFileName(FileDialog.SAVE);
			// get the text handler
			TextHandler txth=(TextHandler)jpe.getTextHandler();	
			// get the selected file				
			OpenFile file=txth.getEditFile();
			// remove the file from the opened list
			ofh.removeFile(file);
			if (file!=null) {
				// set the new name in the file
				file.setName(filename);
				jpe.say("Saving file "+file.getName());
				// save the file under this new name
				file.saveFile();
				// add the file to the opened files again  (now new name)
				ofh.addFile(file);
				jpe.say("Saved file "+file.getName());
			}
		}
	}


	/**
	* save selected file to disk
	*/
	private void saveFile() {
		// get the text handler 
		TextHandler txth=(TextHandler)jpe.getTextHandler();	
		if (txth!=null) {
			// get the selected file from the text handler
			OpenFile file=txth.getEditFile();
			if (file!=null) {
				// signal the use we are saving and save it to disk		
				jpe.say("Saving file "+file.getName());
				file.saveFile();
				jpe.say("Saved file "+file.getName());
			}
		}
	}

	/**
	* get the filename from the user using a file requester
	*/
	private String getFileName(int mode) {
		String prompt;
		String filename;
		String pathname;
		File   file;

		// depending on load or save set the prompt		
		if (mode == FileDialog.LOAD) {
			prompt = "Open File ";
		} else {
			prompt = "Save File As ";
		}

		// create a file requester
		FileDialog d = new FileDialog(jpe.getTextHandler(), prompt, mode);

		// set the file filter (not working on epoc it seems)
		d.setFilenameFilter(new JPEFilenameFilter());

		// set the directory to open in (not working?)
		d.setDirectory("c:\\JPE");

		// show requester (blocks until user is done)
		d.show();

		// optain the filename
		filename = d.getFile();

		// compleet the file name by adding its path 
		pathname = d.getDirectory() + filename; 

		if (filename != null)
		{
			// if we have a filename return it
			return(pathname);
		} else {
			// return null to signal a problem
			return(null);
		}
	}
	/**
	* Handler the ask callback and finish the command started that
	* started with the setAskMode.
	*/
	public void askCallback(String command,String result) {
		if (command.equals("exit")) {
			handleExit(result);
		} else if (command.equals("close")) {
			handleClose(result);
		} 
	}


}
