/*
 * AnchorDialog.java
 *
 * ...
 * ...
 * ...
 */

package aksis.alignment;

// ¤¤¤ ikke sjekket nøyaktig hva vi trenger
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.lang.String;
import java.io.*;
import java.nio.charset.*;
//import java.awt.Toolkit;   // beep
//import aksis.awt2.AwtUtil;   // Oystein flyttet denne inn sammen med alt det andre. den var så ensom der den satt helt for seg selv

class AnchorDialog extends JDialog {

	boolean approved;

	private JButton openFileButton;
	private JButton saveFileButton;
	private JTextArea content;
	private JScrollPane contentScrollPane;
	private JButton useButton;
	private JButton cancelButton;

	protected OpenAction openAction;
	protected SaveAction saveAction;
	
	AlignmentModel model;
	AlignGui gui;
	
	public AnchorDialog(JFrame parent, AlignGui gui, int entryNumber) {
		super(parent, "Anchor word list", true);

		this.gui = gui;
		this.model = gui.model;
	
		OpenAction openAction = new
			OpenAction(
				"Open anchor word file",
				createImageIcon("images/Read.gif", "read from disc"),
				"Open anchor word file",
				new Integer(0)
			);
	
		SaveAction saveAction = new
			SaveAction(
				"Save anchor word file",
				createImageIcon("images/Write.gif", "write to disc"),
				"Save anchor word file",
				new Integer(0)
			);
	
		UseAction useAction = new
			UseAction(
				"Use this anchor word list",
				//createImageIcon("images/Use.gif", "a face"),   // §§§ finnes ikke
				createImageIcon("images/Select.gif", "'ticked' symbol"),
				"Use this anchor word list",
				new Integer(0)
			);
	
		CancelAction cancelAction = new
			CancelAction(
				"Cancel",
				//createImageIcon("images/Cancel.gif", "a face"),   // §§§ finnes ikke
				createImageIcon("images/Cancel.gif", "'X' symbol"),
				"Cancel",
				new Integer(0)
			);
	
		content = new JTextArea();
		contentScrollPane = new JScrollPane(content);
	
		openFileButton = new JButton(openAction);
		openFileButton.setName("O");
	
		saveFileButton = new JButton(saveAction);
		saveFileButton.setName("S");
	
		useButton = new JButton(useAction);
		useButton.setName("U");
	
		cancelButton = new JButton(cancelAction);
		cancelButton.setName("C");
	
	
		Container cp = new Container();
		cp = getContentPane();
		GridBagLayout layout = new GridBagLayout();
		cp.setLayout(layout);
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(3,3,3,3);
		AwtUtil util = new AwtUtil(cp, layout, c);
	
	
		c.gridy = 0;
		c.weighty = 0;
		c.gridx = 0;
		c.gridwidth = 1;
		c.weightx = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
	
		Box b1 = new Box(BoxLayout.X_AXIS);
		b1.add(openFileButton);
		b1.add(Box.createHorizontalGlue());
		b1.add(saveFileButton);
	
		util.addInGridBag(b1);
	
		c.gridy = 1;
		c.weighty = 1;
		c.gridx = 0;
		c.gridwidth = 1;
		c.weightx = 0;
		c.fill = GridBagConstraints.BOTH;
	
		util.addInGridBag(contentScrollPane);
	
		this.model.anchorWordList.display(content);
	
		// ok/cancel buttons
	
		c.gridy = 2;
		c.weighty = 0;
		c.gridx = 0;
		c.gridwidth = 1;
		c.weightx = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
	
		Box b2 = new Box(BoxLayout.X_AXIS);
		b2.add(useButton);
		b2.add(Box.createHorizontalGlue());
		b2.add(cancelButton);
	
		util.addInGridBag(b2);
	
		openFileButton.setMnemonic(KeyEvent.VK_O);
		saveFileButton.setMnemonic(KeyEvent.VK_S);
		useButton.setMnemonic(KeyEvent.VK_U);   // Use
		cancelButton.setMnemonic(KeyEvent.VK_C);
		
		// tool tip
		
		openFileButton.setToolTipText("Open file containing anchor word list, and display the contents");
		saveFileButton.setToolTipText("Save the currently anchor word list to file");
		content.setToolTipText("Area where an anchor word list can be displayed and created/edited");
		useButton.setToolTipText("Use the currently showing anchor word list");   // §§§  (must be saved to file first)????????
		cancelButton.setToolTipText("Don't use the currently showing anchor word list");
		
		// go directly to one particular line?
		
		// ### cludgy
		if (entryNumber >= 0) {
		
			// yes. go directly to one particular line
		
			// hvordan får jeg denne til å rulle til rett linje? contentScrollPane.
			//select(int selectionStart, int selectionEnd);
			String cont = content.getText();
			int pos = 0;
			for (int i=0; i<=entryNumber; i++) {
				int newPos = cont.indexOf("\n", pos);
				if (newPos == -1) {
					pos = cont.length();
					break;
				} else {
					pos = newPos + 1;
				}
				
			}
			pos--;   // go back, before \n. ### what if no \n at very end?
			content.setCaretPosition(pos);
			content.requestFocusInWindow();   // ### funker ikke. må visst gjøres på et helt bestemt tidspunkt
		
		}
	
	
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();   // §§§ ikke brukt
	
		setSize(400, 400);

	}

	public abstract class MyAbstractAction extends AbstractAction {
		public MyAbstractAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
			super(text, icon);
			putValue(SHORT_DESCRIPTION, desc);
			putValue(MNEMONIC_KEY, mnemonic);
		}
	}

	public class OpenAction extends MyAbstractAction {
		public OpenAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
			super(text, icon, desc, mnemonic);
	}

	public void actionPerformed(ActionEvent e) {

		boolean ok;
		if (content.getText().length() == 0) {
			ok = true;
		} else {
			ok = (JOptionPane.showConfirmDialog(
				null,
				"¤¤¤Overwrite current content?",
					//"¤¤¤Title",
				"Error",   // 2006-09-21
				JOptionPane.YES_NO_OPTION,
				JOptionPane.QUESTION_MESSAGE) == 0
			);
		}
	
		if (ok) {
			JFileChooser chooser = new JFileChooser();
			chooser.setApproveButtonText("Open anchor word file");
			if (model.currentOpenDirectory != null) {
				chooser.setCurrentDirectory(model.currentOpenDirectory);
			} else {
				chooser.setCurrentDirectory(null);
			}
			int returnVal = chooser.showOpenDialog(AnchorDialog.this);
				if(returnVal == JFileChooser.APPROVE_OPTION) {
					model.currentOpenDirectory = chooser.getCurrentDirectory();
				}
	
			}
	
		}
	}

	public class SaveAction extends MyAbstractAction {
		public SaveAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {

			String command = e.getActionCommand();
			//System.out.println("command er " + command);

			JFileChooser chooser = new JFileChooser();
			chooser.setApproveButtonText("Save anchor word file");
			if (model.currentSaveDirectory != null) {
				chooser.setCurrentDirectory(model.currentSaveDirectory);
			} else if (model.currentOpenDirectory != null) {
				chooser.setCurrentDirectory(model.currentOpenDirectory);
			} else {
				chooser.setCurrentDirectory(null);
			}

			int returnVal = chooser.showSaveDialog(AnchorDialog.this);
			if(returnVal == JFileChooser.APPROVE_OPTION) {

				File f = chooser.getSelectedFile();

				boolean doSave;
				if(f.exists()) {
					Object[] options = { "Yes", "No" };   // button texts
					int n = JOptionPane.showOptionDialog(
						null,
						f.getAbsolutePath() + "\n" + "already exist.\n\n" + "Overwrite file?",
						"File exists",
						JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE,
						null,
						options,
						options[0]   // the choice that is initially selected
					);
					if(n == 0) {
						doSave = true;
					} else {
						doSave = false;
					}
				} else {
					doSave = true;
				}

				if (doSave) {   // 2006-09-20b. ########ikke testet
					if (saveFile(f)) {
						//...;   ¤¤¤
					} else {
						//...;   ¤¤¤
					}
				}   // 2006-09-20b
			}
		}
	}

	public class UseAction extends MyAbstractAction {
		public UseAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {

			String command = e.getActionCommand();
			ArrayList<String> list = new ArrayList<String>(Arrays.asList(content.getText().split("\\n")));
			AnchorDialog.this.model.anchorWordList.load(list);
			AnchorDialog.this.approved = true;
			AnchorDialog.this.dispose();

		}
	}

	public class CancelAction extends MyAbstractAction {
		public CancelAction(String text, ImageIcon icon, String desc, Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		public void actionPerformed(ActionEvent e) {

			String command = e.getActionCommand();
			AnchorDialog.this.approved = false;
			AnchorDialog.this.dispose();   // ser ut til å funke

		}
	}

	private boolean loadFile(AlignmentModel model, File f) {

        	try {
			InputStream fIn = new FileInputStream(f);
			InputStream bIn = new BufferedInputStream(fIn);
			Charset cs = Charset.forName("UTF-8");
			InputStreamReader in = new InputStreamReader(bIn, cs);

			int iChar;
			while ((iChar = in.read()) != -1) {
				content.append("" + (char)iChar);
			}
			in.close();

			model.setAnchorFilename(f.getName());
			gui.setAnchorFilenameLabel(f.getName());

		return true;

        	} catch (Exception e) {
	            ErrorMessage.error("Can't load file " + f.getName() + "\nException:\n" + e.toString());   // 2006-09-21

        	    return false;

        }

    }

	private boolean saveFile(File f) {
		try {
			OutputStream fOut = new FileOutputStream(f);
			OutputStream bOut = new BufferedOutputStream(fOut);
			Charset cs = Charset.forName("UTF-8");
			OutputStreamWriter out = new OutputStreamWriter(bOut, cs);
	
			out.write(content.getText(), 0, content.getText().length());
			out.close();
	
			model.setAnchorFilename(f.getName());
			gui.setAnchorFilenameLabel(f.getName());
	
			return true;
	
		} catch (Exception e) {
			ErrorMessage.error("Can't save file " + f.getName() + "\nException:\n" + e.toString());
			
			return false;
		}
	}

	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createImageIcon(String path, String description) {
		java.net.URL imgURL = AnchorDialog.class.getResource(path);
		if (imgURL != null) {
			return new ImageIcon(imgURL, description);
		} else {
			return null;
		}
	}

}
