//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010 huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/god4j
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : god4j@lists.sourceforge.net 
 */
//----------------------------END  LICENSE-----------------------------
package org.huihoo.god4j.editor;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

import org.huihoo.god4j.GOD4JConstants;
import org.huihoo.god4j.editor.panels.JavaGroupPanel;
import org.huihoo.god4j.editor.panels.JavaPanel;
import org.huihoo.god4j.util.ImageLoader;
import org.huihoo.god4j.util.StringManager;
/**
 * @author reic
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class JavaDialog extends JDialog
{
	protected static StringManager sm = StringManager.getManager("org.huihoo.god4j.editor");

	private JButton buttonOK;
	private JButton buttonCancel;

	private JavaPanel panelToEdit = new JavaPanel();
	private WindowListener wl = new WindowAdapter()
	{
		public void windowClosing(WindowEvent e)
		{
			isCanceled = true;
			dispose();
		}
	};
	/** Set to true if cancel hasn't been pressed */
	private boolean isCanceled = false;

	/**
	* Constructs a new modal unparented instance that will define new element.
	*/
	public JavaDialog()
	{
		this((JFrame) null, "");
	}
	/**
	* Constructs a new modal instance which parent is <code>parent</code> and
	* proceeds a title of dialog.
	*
	* @param parent Parent frame.
	* @param title  Dialog title.
	*/
	public JavaDialog(JFrame parent, String title)
	{
		this(parent, title, true);
	}
	/**
	* Constructs a new modal instance which parent is <code>parent</code> and
	* proceeds a title of dialog.
	*
	* @param parent Parent dialog.
	* @param title  Dialog title.
	*/
	public JavaDialog(JDialog parent, String title)
	{
		this(parent, title, true);
	}
	/**
	* Constructs a new modal instance which parent is <code>parent</code> and
	* proceeds a title of dialog.
	*
	* @param parent  Parent frame.
	* @param title   Dialog title.
	* @param isModal true if dialog is modal.
	*/
	public JavaDialog(JFrame parent, String title, boolean isModal)
	{
		super(parent, title, isModal);
		initDialog();
	}
	/**
	* Constructs a new modal instance which parent is <code>parent</code> and
	* proceeds a title of dialog.
	*
	* @param parent Parent dialog.
	* @param title  Dialog title.
	* @param isModal true if dialog is modal.
	*/
	public JavaDialog(JDialog parent, String title, boolean isModal)
	{
		super(parent, title, isModal);
		initDialog();
	}

	/**
	* @return <tt>true</tt> if cancel hasn't been pressed,
	*         <tt>false</tt> otherwise.
	*/
	public boolean isCanceled()
	{
		return isCanceled;
	}
	public void setCanceled(boolean isCanceled)
	{
		this.isCanceled = isCanceled;
	}

	/**
	* Displays dialog and adds specified panel to it, along
	* with OK and/or Cancel button. The dialog allows user to edit
	* the panel field(s) that represents corresponding member of
	* it's owner class. After user presses OK, the content of
	* panel field(s) is transfered to the corresponding owner
	* class member. The member(s) of owner class represent a
	* program equivalent for real XPDL entity.
	*
	* @param elementPanel The panel with visual presentation of it's
	*                     owner members.
	*/
	public void editXPDLComponent(JavaPanel elementPanel, boolean hasCancelButton, boolean doNotClose)
	{
		if (elementPanel.getXPDLComponent() != null)
		{
			elementPanel.getXPDLComponent().loadComponent();
		}

		Container cp = getContentPane();
		cp.remove(panelToEdit);
		panelToEdit = elementPanel;
		cp.add(panelToEdit, 0);
		pack();
		// doNotClose is true only for dialog for entering
		// unique package Id - when we start to edit new package
		if (doNotClose)
		{
			removeWindowListener(wl);
			getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(
				KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false));
		}
		if (hasCancelButton)
		{
			buttonCancel.setVisible(true);
		}
		else
		{
			buttonCancel.setVisible(false);
			if (!doNotClose)
			{
				buttonOK.requestFocus();
			}
		}
		setLocationRelativeTo(getParent());

		show();
		requestFocus();
	}
	private void initDialog()
	{
		setFont(GOD4JConstants.WINDOWS_UI_FONT);
		
		try
		{
			JPanel buttonPanel = new JPanel();
			buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
			buttonPanel.setAlignmentY(Component.TOP_ALIGNMENT);
			buttonOK = new JButton(sm.getString("OKKey"));
			ImageIcon icon = ImageLoader.getImageIcon(ImageLoader.getImageName("OKImage"));
			if (icon != null)
			{
				buttonOK.setIcon(icon);
			}

			buttonCancel = new JButton(sm.getString("CancelKey"));
			icon = ImageLoader.getImageIcon(ImageLoader.getImageName("CancelImage"));
			if (icon != null)
			{
				buttonCancel.setIcon(icon);
			}

			buttonPanel.add(buttonOK);
			buttonPanel.add(buttonCancel);
			Container cp = getContentPane();
			cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
			cp.add(panelToEdit);
			cp.add(buttonPanel);
			// action listener for confirming
			buttonOK.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent ae)
				{
					if (panelToEdit.getXPDLComponent().isReadOnly())
					{
						dispose();
					}
					else if (canApplyChanges())
					{
						applyChanges();

						dispose();
					}
				}
			});
			// action listener for canceling
			buttonCancel.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent ae)
				{
					isCanceled = true;
					dispose();
				}
			});
			addWindowListener(wl);
			getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
				KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false),
				"Cancel");
			getRootPane().getActionMap().put("Cancel", new AbstractAction()
			{
				public void actionPerformed(ActionEvent e)
				{
					isCanceled = true;
					dispose();
				}
			});
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(getParent());
		buttonOK.setDefaultCapable(true);
		getRootPane().setDefaultButton(buttonOK);
	}

	//------------------------------------------------------------------
	//------------------------------------------------------------------
	public boolean canApplyChanges()
	{
		if (panelToEdit.checkRequired())
		{
			XPDLComponent xpComp = panelToEdit.getXPDLComponent();
			if (!xpComp.isInputValid(panelToEdit))
			{
				return false;
			}
			
			if (xpComp instanceof XPDLCollectionComponent)
			{
				if (((XPDLCollectionComponent) xpComp).nameIsUniqueAndValid(panelToEdit))
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return true;
			}
		}
		else
		{
			return false;
		}
	}

	public void applyChanges()
	{
		panelToEdit.applyChanges();
		panelToEdit.getXPDLComponent().saveComponent();
	}

	public void requestFocus()
	{
		try
		{
			if (panelToEdit instanceof JavaGroupPanel)
			{
				if (panelToEdit.getComponent(0).isEnabled())
				{
					panelToEdit.getComponent(0).requestFocus();
				}
				else
				{
					panelToEdit.getComponent(1).requestFocus();
				}
			}
		}
		catch (Exception ex)
		{
			panelToEdit.requestFocus();
		}
	}
}