package lu.tudor.santec.gecamed.esante.gui.dialogs;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.EventObject;
import java.util.HashSet;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer;
import lu.tudor.santec.gecamed.esante.ejb.entity.beans.ESanteProperty;
import lu.tudor.santec.gecamed.esante.ejb.session.beans.ESanteConfigManagerBean;
import lu.tudor.santec.gecamed.esante.ejb.session.interfaces.ESanteConfigManager;
import lu.tudor.santec.gecamed.esante.gui.utils.ESanteGuiUtils;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * @author jens.ferring(at)tudor.lu
 * 
 * @version
 * <br>$Log: EHealthIdEditDialog.java,v $
 * <br>Revision 1.2  2014-02-04 10:08:38  ferring
 * <br>eSante ID management completed
 * <br>Only those documents will be shown, that are retrieved by the RSQ
 * <br>
 * <br>Revision 1.1  2014-01-29 16:57:50  donak
 * <br>Renamed references to HPD to eHealth in respect to the request of the eHealth Agency
 * <br>Removed template DSP-11-12 as it is not needed and was created only for internal testing purposes
 * <br>
 * <br>Revision 1.2  2014-01-28 17:55:31  donak
 * <br>adapted constants as term HDP ID should be replaced by eHealth ID
 * <br>
 * <br>Revision 1.1  2014-01-28 16:02:44  ferring
 * <br>eHealth ID management implemented
 * <br>
 */

public class EHealthIdEditDialog extends ESanteDialog implements MouseListener
{
	/* ======================================== */
	// CONSTANTS
	/* ======================================== */
	
	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(EHealthIdEditDialog.class.getName());
	
	private static final long	serialVersionUID	= 1L;
	
	private static final String	COLUMN_TITLE_OWNER	= Translatrix.getTranslationString("esante.managementPanel.objectId.manageEHealthIds.columnOwner");
	private static final String	COLUMN_TITLE_REF_ID	= Translatrix.getTranslationString("esante.managementPanel.objectId.manageEHealthIds.columnRefId");
	private static final String	COLUMN_TITLE_EHEALTH_ID	= Translatrix.getTranslationString("esante.managementPanel.objectId.manageEHealthIds.columnEHealthId");
	
	public static final int	COLUMN_INDEX_OWNER	= 0;
	public static final int	COLUMN_INDEX_REF_ID	= 1;
	public static final int	COLUMN_INDEX_EHEALTH_ID	= 2;
	
	public static final String[] COLUMN_IDENTIFIERS	= new String[] 
	{
		COLUMN_TITLE_OWNER,
		COLUMN_TITLE_REF_ID,
		COLUMN_TITLE_EHEALTH_ID
	};
	
	
	
	/* ======================================== */
	// MEMBERS
	/* ======================================== */
	
	private static EHealthIdEditDialog		instance;
	
	
	private CellEditor			cellEditor	= new CellEditor();
//	private TableCellEditor		cellEditor	= this;
//	private TableCellRenderer	cellRenderer= new LineColorCellRenderer();
	
	private	JTable				table;
	
	private EHealthIdTableModel	model;
	
	private JPopupMenu			contextMenu;
	
	private JMenuItem			addMenuItem;
	
	private JMenuItem			removeMenuItem;
	
	private boolean				editable;
	
	
	
	/* ======================================== */
	// CONSTRUCTORS
	/* ======================================== */
	
	private EHealthIdEditDialog ()
	{
		super(MainFrame.getInstance(), 
				Translatrix.getTranslationString("esante.managementPanel.objectId.manageEHealthIds"), 
				OK_CANCEL_BUTTON_MODE);
		
		JScrollPane		scroller;
		CellConstraints	cc			= new CellConstraints();
		JLabel			description	= new JLabel(Translatrix.getTranslationString(
				"esante.managementPanel.objectId.manageEHealthIds.description"));
		
		
		model		= new EHealthIdTableModel();
		
		table		= new JTable(model);
		table.addMouseListener(this);
		table.getColumnModel().getColumn(COLUMN_INDEX_OWNER).setCellRenderer(cellEditor);
		table.getColumnModel().getColumn(COLUMN_INDEX_OWNER).setCellEditor(cellEditor);
		table.getColumnModel().getColumn(COLUMN_INDEX_REF_ID).setCellRenderer(cellEditor);
		table.getColumnModel().getColumn(COLUMN_INDEX_REF_ID).setCellEditor(cellEditor);
		table.getColumnModel().getColumn(COLUMN_INDEX_EHEALTH_ID).setCellRenderer(cellEditor);
		table.getColumnModel().getColumn(COLUMN_INDEX_EHEALTH_ID).setCellEditor(cellEditor);
		
		scroller	= new JScrollPane(table);
		scroller.setOpaque(false);
		scroller.getViewport().setOpaque(false);
		
		mainPanel.setLayout(new FormLayout("5px,f:d:g,5px", "5px,f:p,10px,f:d:g,5px"));
		mainPanel.add(description,	cc.xy(2, 2));
		mainPanel.add(scroller,		cc.xy(2, 4));
		
		// create the context menu
		contextMenu	= new JPopupMenu();
		contextMenu.setBackground(GECAMedColors.c_GECAMedBackground);
		
//		addMenuItem		= new JMenuItem(new AbstractAction(
//				Translatrix.getTranslationString("esante.managementPanel.objectId.manageEHealthIds.addEntry"),
//				GECAMedModule.getSmallIcon(GECAMedIconNames.ADD_LINE))
//		{
//			private static final long	serialVersionUID	= 1L;
//
//			public void actionPerformed (ActionEvent e)
//			{
//				addProperty();
//			}
//		});
//		addMenuItem.setOpaque(false);
//		contextMenu.add(addMenuItem);
		
		removeMenuItem		= new JMenuItem(new AbstractAction(
				Translatrix.getTranslationString("esante.managementPanel.objectId.manageEHealthIds.deleteEntry"),
				GECAMedModule.getSmallIcon(GECAMedIconNames.REMOVE_LINE))
		{
			private static final long	serialVersionUID	= 1L;

			public void actionPerformed (ActionEvent e)
			{
				deleteSelectedProperty();
			}
		});
		removeMenuItem.setOpaque(false);
		contextMenu.add(removeMenuItem);
	}
	
	
	
	/* ======================================== */
	// CLASS BODY
	/* ======================================== */
	
	public static void showDialog ()
	{
		if (instance == null)
			instance = new EHealthIdEditDialog();
		
		instance.pack();
		instance.showCenteredDialog();
	}
	
	
	@Override
	public void prepareToShowUp ()
	{
		ESanteConfigManager		manager				= ESanteConfigManagerBean.getInstance();
		List<ESanteProperty>	userInfo			= manager.getESanteUserProperties(ESanteProperty.PROP_ESANTE_USER_INFO);
		List<ESanteProperty>	eHealthIds			= manager.getESanteUserProperties(ESanteProperty.PROP_USER_EHEALTH_ID);
		ESanteProperty			practiceEHealthId	= manager.getESanteProperty(ESanteProperty.PROP_PRACTICE_EHEALTH_ID);
		
		model.setData(userInfo, eHealthIds, practiceEHealthId);
	}
	
	
	@Override
	public void okActionCalled ()
	{
//		Collection<ESanteProperty> properties2Save	= model.getChangedProperties();
//		Collection<ESanteProperty> properties2Delete= model.getRemovedProperties();
//		
//		
//		if (properties2Save != null && !properties2Save.isEmpty())
//			ESanteConfigManagerBean.getInstance().saveESanteProperties(properties2Save);
//		
//		if (properties2Delete != null && !properties2Delete.isEmpty())
//			ESanteConfigManagerBean.getInstance().deleteProperties(properties2Delete);
		
		super.okActionCalled();
	}
	
	
	/* ---------------------------------------- */
	// MOUSE LISTENER METHODS
	/* ---------------------------------------- */
	
	public void mouseClicked (MouseEvent e)
	{
		if (e.getClickCount() >= 2)
		{
			int row		= table.rowAtPoint(e.getPoint());
			int column	= table.columnAtPoint(e.getPoint());
			
			if (row == 0 && column < COLUMN_INDEX_EHEALTH_ID)
				return;
			
			editable	= true;
			table.editCellAt(row, column);
		}
	}
	
	
	public void mousePressed (MouseEvent e)
	{
		if (e.isPopupTrigger())
			showContextMenu(e);
	}
	
	
	public void mouseReleased (MouseEvent e)
	{
		if (e.isPopupTrigger())
			showContextMenu(e);
	}
	
	
	public void mouseEntered (MouseEvent e) {}
	public void mouseExited (MouseEvent e) {}
	
	
	
	/* ======================================== */
	// HELP METHODS
	/* ======================================== */
	
	private void showContextMenu (MouseEvent e)
	{
		int clickedRow = table.rowAtPoint(e.getPoint());
		
//		addMenuItem.setEnabled(clickedRow > 0);
		
		table.getSelectionModel().setSelectionInterval(clickedRow, clickedRow);
		contextMenu.show(table, e.getX(), e.getY());
	}
	
	
	private void deleteSelectedProperty ()
	{
		String eSanteUserID = null;
		int row = table.getSelectedRow();
		if (row < 0 ) return;
		
		try {
			eSanteUserID = (String) model.getValueAt(row, EHealthIdEditDialog.COLUMN_INDEX_REF_ID);
			ESanteGuiUtils.deleteEsanteUser(eSanteUserID);
			
			model.removeProperty(row);	
			
		} catch (Exception e) {
			logger.warn("Error deleting esante user: " + eSanteUserID, e);
		}

	}
	
	
//	private void addProperty ()
//	{
//		model.addProperty();
//	}
	
	
	
	/* ======================================== */
	// CLASS: CellEditor
	/* ======================================== */
	
	private class CellEditor extends LineColorCellRenderer implements TableCellEditor
	{
		/* ======================================== */
		// CONSTANTS
		/* ======================================== */
		
		private static final long	serialVersionUID	= 1L;
		
		
		
		/* ======================================== */
		// MEMBERS
		/* ======================================== */
		
		private JTextField	editor	= new JTextField();
		
		private String		oldValue;
		
		private int			editingColumn;
		
		private int			editingRow;
		
		private Collection<CellEditorListener> listener	= new HashSet<CellEditorListener>();
		
		
		
		/* ======================================== */
		// CLASS BODY
		/* ======================================== */
		
		public Object getCellEditorValue ()
		{
			return editor.getText();
		}
		
		
		public boolean isCellEditable (EventObject anEvent)
		{
			return editable;
		}
		
		
		public boolean shouldSelectCell (EventObject anEvent)
		{
			return true;
		}
		
		
		public boolean stopCellEditing ()
		{
			ChangeEvent e = new ChangeEvent(table);
			
			
			model.setValueAt(editor.getText(), editingRow, editingColumn);
			
			editable	= false;
			table.editingStopped(e);
			for (CellEditorListener l : listener)
				l.editingStopped(e);
			
			return true;
		}
		
		
		public void cancelCellEditing ()
		{
			ChangeEvent e = new ChangeEvent(table);
			for (CellEditorListener l : listener)
				l.editingCanceled(e);
		}
		
		
		public void addCellEditorListener (CellEditorListener l)
		{
			listener.add(l);
		}
		
		
		public void removeCellEditorListener (CellEditorListener l)
		{
			listener.remove(l);
		}
		
		
		public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column)
		{
			oldValue		= String.valueOf(value == null ? "" : value);
			editingRow		= row;
			editingColumn	= column;
			editor.setText(oldValue);
			
			return editor;
		}
		
		
		@Override
		public Component getTableCellRendererComponent (JTable p_Table, Object value, 
				boolean p_IsSelected, boolean hasFocus, int p_Row, int p_Column)
		{
			JLabel	cell	= (JLabel) super.getTableCellRendererComponent(
					p_Table, value, p_IsSelected, hasFocus, p_Row, p_Column);
			
			
			cell.setEnabled(p_Row != 0 || p_Column == COLUMN_INDEX_EHEALTH_ID);
			
			return cell;
		}
	}
}
