package lu.tudor.santec.gecamed.patient.gui.history.contextmenu;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.Date;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.IconFetcher;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.LineColorListRenderer;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.history.FileHandler;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * @author jens.ferring(at)tudor.lu
 * 
 * @version
 * <br>$Log: ChangeIncidentDialog.java,v $
 * <br>Revision 1.4  2013-02-13 14:43:35  gbosch
 * <br>Provisionary fix for deployment problem related to MainFrame class.
 * <br>
 * <br>Revision 1.3  2013-02-13 14:01:58  ferring
 * <br>history will not always be reloaded completely
 * <br>
 * <br>Revision 1.2  2013-02-13 10:51:10  ferring
 * <br>create new incident button added
 * <br>
 * <br>Revision 1.1  2013-02-08 15:27:17  ferring
 * <br>Option added for files and letters to attach them to another incident
 * <br>
 */

public class ChangeIncidentDialog extends GECAMedBaseDialogImpl
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long	serialVersionUID	= 1L;
	
//	private static final Rectangle	UPPER_CORNER		= new Rectangle(0, 0, 0, 0);
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
//	private static IncidentManager	manager;
	
	
	private IncidentList		incidentList;
	
	private DefaultListModel	incidentListModel;
	
	private IncidentEntry		originalEntry;
	
	private int					originalIncidentIndex;
	
	private JButton				createNewIncident;
	
	private Incident			selectedIncident;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	public ChangeIncidentDialog ()
	{
		super(MainFrame.getInstance(), 
				Translatrix.getTranslationString("History.changeIncident.dialogTitle"), 
				OK_CANCEL_BUTTON_MODE);
		
		initComponents();
//		manager	= (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
	}
	
	
	
	/* ======================================== */
	// 		CLASS BODY
	/* ======================================== */
	
	public Incident showDialog (IncidentEntry entry)
	{
		Collection<Incident>	incidents;
		
		
		// initialise the GUI elements
		originalEntry	= entry;
		selectedIncident= null;
		
		// load the incidents from the history
		incidents	= PatientManagerModule.getInstance().getPatientPanel()
				.getHistoryDataAgent().getIncidents().values();
//		incidents	= manager.getIncidentsOfPatient(entry.getIncident().getPatientId());
		incidentListModel.removeAllElements();
		
		for (Incident i : incidents)
			incidentListModel.addElement(i);
		
		originalIncidentIndex	= incidentListModel.indexOf(originalEntry.getIncident());
		incidentList.scrollTo(originalEntry.getIncident());
		
		// show the dialog
		this.setLocationRelativeTo(this.getOwner());
		this.pack();
		this.setVisible(true);
		
		return selectedIncident;
	}
	
	
	@Override
	public void okActionCalled()
	{
		selectedIncident	= (Incident) incidentList.getSelectedValue();
		super.okActionCalled();
	}
	
	
	private void createNewIncident ()
	{
		Date		now			= new Date();
		int			userId		= GECAMedModule.getCurrentUser().getId();
		Incident	orgIncident	= originalEntry.getIncident();
		
		
		// define the new incident
		selectedIncident = new Incident();
		selectedIncident.setCreated(now);
		selectedIncident.setCreatedBy(userId);
		selectedIncident.setIncidentDate(now);
		selectedIncident.setIsAccident(false);
		selectedIncident.setModified(now);
		selectedIncident.setModifiedBy(userId);
		selectedIncident.setPhysicianId(orgIncident.getPhysicianId());
		selectedIncident.setPatientId(orgIncident.getPatientId());
		selectedIncident.setSiteId(orgIncident.getSiteId());
		
		super.okActionCalled();;
	}
	
	
	
	/* ======================================== */
	// 		HELP METHODS
	/* ======================================== */
	
	private void initComponents()
	{
		JLabel			description;
		JScrollPane		scroller;
		int				width;
		int				height;
		CellConstraints	cc	= new CellConstraints();
		
		
		description			= new JLabel(Translatrix.getTranslationString("History.changeIncident.dialogDescription"));
		
		incidentListModel	= new DefaultListModel();
		incidentList		= new IncidentList(incidentListModel);
		incidentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		incidentList.setCellRenderer(new ChangeIncidentCellRenderer());
		incidentList.addListSelectionListener(new ListSelectionListener()
		{
			public void valueChanged(ListSelectionEvent e)
			{
				okButton.setEnabled(incidentList.getSelectedIndex() >= 0);
			}
		});
		okButton.setEnabled(incidentList.getSelectedIndex() >= 0);
		incidentList.addMouseListener(new MouseAdapter()
		{
			public void mouseClicked(MouseEvent e) 
			{
				if (!e.isPopupTrigger() && e.getClickCount() > 1)
				{
					if (incidentList.getLastClicked() != originalIncidentIndex)
						okActionCalled();
				}
			}
		});
		
		
		scroller			= new JScrollPane(incidentList);
		scroller.setOpaque(false);
		scroller.getViewport().setOpaque(false);
		
		// define the layout and add components
		mainPanel.setLayout(new FormLayout("5px, f:p:g, 5px", "5px, f:p, 10px, f:p:g, 5px"));
		mainPanel.add(description,	cc.xy(2, 2));
		mainPanel.add(scroller,		cc.xy(2, 4));
		
		// add the new incident button
		createNewIncident	= new JButton(new AbstractAction(
				Translatrix.getTranslationString("History.changeIncident.newIncident"),
				IconFetcher.getSmallIcon(PatientManagerModule.class, "new_folder.png"))
		{
			private static final long	serialVersionUID	= 1L;
			
			public void actionPerformed(ActionEvent e)
			{
				createNewIncident();
			}
		});
		addButton(createNewIncident);
		
		// define the size of the dialog
		this.pack();
		width	= this.getWidth();
		height	= this.getHeight();
		
		if (getOwner().getWidth() < width)
			width = getOwner().getWidth();
		
		if (getOwner().getHeight() < height)
			height = getOwner().getHeight();
		
		this.setSize(width, height);
	}
	
	
	
	/* ======================================== */
	// 		CLASS: ChangeIncidentCellRenderer
	/* ======================================== */
	
	private class ChangeIncidentCellRenderer extends LineColorListRenderer
	{
		/* ======================================== */
		// 		CONSTANTS
		/* ======================================== */
		
		private static final long	serialVersionUID	= 1L;
		
		
		
		/* ======================================== */
		// 		CLASS BODY
		/* ======================================== */
		
		@Override
		public Component getListCellRendererComponent(JList list, Object value, 
				int index, boolean isSelected, boolean cellHasFocus)
		{
			Incident		incident	= (Incident) value;
			JLabel			cell;
			
			
			cell		= (JLabel) super.getListCellRendererComponent(
					list, FileHandler.getHistoryText(incident), index, isSelected, cellHasFocus);
			
			if (incident.equals(originalEntry.getIncident()))
			{
				cell.setForeground(Color.DARK_GRAY);
				cell.setBackground(Color.LIGHT_GRAY);
				cell.setBorder(BorderFactory.createEmptyBorder());
			}
			
			return cell;
		}
	}
	
	
	
	/* ======================================== */
	// 		CLASS: DisableCellListListener
	/* ======================================== */
	
	private class IncidentList extends JList
	{
		/* ======================================== */
		// 		CONSTANTS
		/* ======================================== */
		
		private static final long	serialVersionUID	= 1L;
		
		
		
		/* ======================================== */
		// 		MEMBERS
		/* ======================================== */
		
		private int	lastClicked	= -1;
		
		
		
		/* ======================================== */
		// 		CONSTRUCTORS
		/* ======================================== */
		
		public IncidentList(ListModel model)
		{
			super(model);
		}
		
		
		
		/* ======================================== */
		// 		CLASS BODY
		/* ======================================== */
		
		@Override
		public void setSelectedIndex(int index)
		{
			if (index < 0 || selectEntry((Incident) getModel().getElementAt(index)))
				super.setSelectedIndex(index);
		}
		
		
		@Override
		public void setSelectedValue(Object anObject, boolean shouldScroll)
		{
			if (anObject == null || selectEntry((Incident) anObject))
				super.setSelectedValue(anObject, shouldScroll);
		}
		
		
		@Override
		public void setSelectionInterval(int anchor, int lead)
		{
			lastClicked	= anchor;
			
			for (int index = anchor; index <= lead; index++)
			{
				if (!selectEntry((Incident) getModel().getElementAt(index)))
					return;
			}
			
			super.setSelectionInterval(anchor, lead);
		}
		
		
		public void scrollTo (Incident incident)
		{
			super.setSelectedValue(incident, true);
			super.setSelectedIndex(-1);
		}
		
		
		public int getLastClicked ()
		{
			return lastClicked;
		}
		
		
		
		/* ======================================== */
		// 		HELP METHODS
		/* ======================================== */
		
		private boolean selectEntry (Incident incident)
		{
			return !(incident != null && incident.equals(originalEntry.getIncident()));
		}
	}
}
