/*
 * Created on 09.02.2004 21:55:06
 *
 * Multimediale Algorithmen und Datenstrukturen Assessments
 */
package evaluation;

import mauda.*;
import mauda.utils.*;
import mauda.evaluation.*;

import help.HelpFrame;
import help.HelpTree;

import java.awt.event.*;
import java.util.*;
import javax.swing.*;

import java.io.*;
import java.beans.*;

/**
 * The listener for menu- and toolbar-actions
 * 
 * @author Markus Krebs
 */
public class MenuToolBarListener implements ActionListener {

	private EvalExercise exercise;

	private JFileChooser fileChooser;
	private PreviewPanel previewPanel = new PreviewPanel();
	
	/**
	 * Creates the listener for menu and toolbar-actions
	 * @param exercise EvalExercise
	 */
	public MenuToolBarListener(EvalExercise exercise) {
		this.exercise = exercise;
		fileChooser = new JFileChooser(FileLocation.completedPath);
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.addChoosableFileFilter(new XMLFilter());
		fileChooser.setMultiSelectionEnabled(false); // Mehrfachselektion AUS
		fileChooser.setAccessory(previewPanel);
		fileChooser.addPropertyChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent e) {
				if(e.getPropertyName().equals(
									 JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
					File f = (File)e.getNewValue();
					if(f==null) return;
					String s = f.getPath(), suffix = null;
					int i = s.lastIndexOf('.');

					if(i > 0 && i < s.length() - 1)
						suffix = s.substring(i+1).toLowerCase();

					if(suffix!=null&&suffix.equals("xml"))
						previewPanel.configure(f);
				}
			}
		});
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		if(!exercise.actionsAllowed()) return;
		String s = e.getActionCommand();
		//System.out.println("ActionCommand: "+s);
		if(s == ActionCommands.openFile) {
			MetaData.setDisplayMode(MetaData.EVALUATOR);
			fileChooser.setCurrentDirectory(new File(FileLocation.completedPath));
			openFile();
		} else if(s == ActionCommands.saveFile) {
			MetaData.setDisplayMode(MetaData.EVALUATOR);
			fileChooser.setCurrentDirectory(new File(FileLocation.evaluatedPath));
			saveFile(exercise.getFilename());
		} else if(s == ActionCommands.saveAsFile) {
			MetaData.setDisplayMode(MetaData.EVALUATOR);
			fileChooser.setCurrentDirectory(new File(FileLocation.evaluatedPath));
			saveAsFile();
		} else if(s == ActionCommands.meta) {
			boolean mod = exercise.getMetaData().inputDialog();
			if(mod) exercise.setModified(true);
		} else if(s == ActionCommands.exit) {
			if(dialogDiscardActiveExercise()) System.exit(0);
		} else if(s == ActionCommands.showAbout) {
			AboutFrame.createAndShowGUI();
		} else if(s == ActionCommands.showHelp) {
			HelpTree.setView(HelpTree.EVALEDITOR_VIEW);
			HelpFrame.createAndShowGUI();
		}
	}
	/**
	 * Opens a file by showing an filechooser, and then calls
	 * <code>openFile(File)</code>
	 * @see evaluation.MenuToolBarListener#openFile(File)
	 */
	private void openFile() {
		if(!dialogDiscardActiveExercise()) return;
		int state = fileChooser.showOpenDialog(null);
		if(state == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if(file.isFile()) {
				openFile(file);				
			}
		}
	}
	/**
	 * Opens the specified file
	 * @param file The file-Object
	 */
	private void openFile(File file) {
		Vector opVector = null;
		
		exercise.setFilename(file.getAbsolutePath());
		
		HashMap hm = exercise.load(exercise.getFilename());
		if(hm==null) return;	// <-- Sollte nie vorkommen (falls PlugIn nicht existiert)
		
		String editorState = exercise.getMetaData().getEditorState();
		String evaluatorState = exercise.getMetaData().getEvaluatorState();
		
		if(editorState.equals("completed")) {
			exercise.load(hm);
			exercise.loadConfig(hm);
		} else {
			JOptionPane.showMessageDialog(MAUDA.getApplicationMainFrame(), "Cant load an uncompleted exercise!");
			return;
		}

		exercise.loadCompleted(hm);
		
		// Damit bei save ohne FileChooser nicht die Aufgabe über-
		// schrieben wird!
		exercise.setDefaultFilename();
		return;
	}
	/**
	 * Saves the current exercise to the specified filename
	 * @param fname filename
	 */
	private void saveFile(String fname) {
		if(fname.equals(exercise.getDefaultFilename())) {
			JOptionPane.showMessageDialog(MAUDA.getApplicationMainFrame(), Prop.get(this, "DialogChooseSaveAs"));
			return;
		}
		//exercise.getMetaData().inputDialog();
		exercise.saveEvaluated(fname);
		exercise.setFilename(fname);
	}
	
	/**
	 * Opens a filechooser and then saves the current exercise to
	 * the chosen file.
	 */
	private void saveAsFile() {
		int state = fileChooser.showSaveDialog(null);
		if(state == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if(file!=null) {
				String fname = file.getAbsolutePath();
				if(file.exists()&&!dialogExistsOverwrite(fname)) {
					JOptionPane.showMessageDialog(MAUDA.getApplicationMainFrame(), Prop.get(this,"FileNotSaved"));
					return;
				}
				if(!fname.toLowerCase().endsWith(".xml")) {
					fname = fname + ".xml";
				}
				saveFile(fname);
			}
		}
	}
	/**
	 * When a file already exists, this methods displays a warning
	 * overwrite-message that the user has to confirm.
	 * @param filename Filename
	 * @return Returns true when overwrite is ok, false otherwise
	 */
	private boolean dialogExistsOverwrite(String filename) {
		String s = Prop.get(this,"DialogExistsOverwrite");
		s = s.replaceAll("FILENAME", filename);
		int result = JOptionPane.showConfirmDialog(MAUDA.getApplicationMainFrame(), s, Prop.get(this,"DialogExistsOverwriteTitle"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
		if(result == JOptionPane.YES_OPTION) { return true; }
		//else if(result == JOptionPane.NO_OPTION) { return false; }
		//else if(result == JOptionPane.CANCEL_OPTION) { return false; }
		return false;
	}
		
	/**
	 * Shows a dialog where the user have to choose if he want to
	 * discard the current exercise
	 * @return Returns true when the actual exercise ok to discard
	 */
	private boolean dialogDiscardActiveExercise() {
		if(!exercise.isModified()) return true;
		String s = Prop.get(this,"DialogDiscardActiveExercise");
		int result = JOptionPane.showConfirmDialog(MAUDA.getApplicationMainFrame(), s, Prop.get(this,"DialogDiscardActiveExerciseTitle"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
		if(result == JOptionPane.YES_OPTION) { return true; }
		//else if(result == JOptionPane.NO_OPTION) { return false; }
		//else if(result == JOptionPane.CANCEL_OPTION) { return false; }
		return false;		
	}

}
