/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
/**
 *
 */
package lu.tudor.santec.gecamed.prescription.gui.widgets.editor;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

import lu.tudor.santec.gecamed.core.gui.GECAMedAction;
import lu.tudor.santec.gecamed.core.gui.GECAMedFonts;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.GECAMedTab;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.gui.incident.IncidentControler;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.gui.PrescriptionIcons;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.antecedents.AntecedentPrescriptionControler;
import lu.tudor.santec.gecamed.prescription.gui.widgets.editor.template.TemplateControler;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * This tab is made of steel.
 * All editor components and template parts and antecedent tools are placed in it.
 * It owns also the "Print" button to print prescriptions.
 * 
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: PrescriptionTab.java,v $
 * <br>Revision 1.14  2013-12-27 18:09:24  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.13  2010-03-30 10:40:44  troth
 * <br>Redesign of the prescription view - change icon manager class
 * <br>
 * <br>Revision 1.12  2008-10-22 14:20:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.11  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.10  2008-07-23 15:13:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.9  2008-05-13 11:53:41  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2008-05-13 09:33:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.7  2008-05-09 15:24:16  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.6  2008-01-16 15:33:35  heinemann
 * <br>better documentation
 * <br>
 * <br>Revision 1.5  2007/07/04 08:50:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2007/06/18 11:31:36  hermen
 * <br>cleanup of old stuff and moved some beans
 * <br>
 * <br>Revision 1.3  2007/03/12 14:32:10  heinemann
 * <br>Complete - # 46: make printed prescriptions editable
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/46
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:42  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.16  2007/02/21 10:00:40  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.15  2007/01/24 12:48:56  heinemann
 * <br>consultation and prescription update control.
 * <br>Modifications are displayed.
 * <br>And Incidents are not created if nothing has been entered in consultation, accident and prescription
 * <br>
 * <br>Revision 1.1.2.14  2007/01/22 10:24:07  heinemann
 * <br>Incomplete - # 13: print copies of prescriptions
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/13
 * <br>
 * <br>Revision 1.1.2.13  2007/01/19 12:44:17  heinemann
 * <br>Complete - # 28: Accident Nr and date must appear on the prescription printout
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/28
 * <br>
 * <br>Revision 1.1.2.12  2007/01/19 10:34:57  heinemann
 * <br>Incomplete - # 55: Check if a modified incident keeps it original date
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/55
 * <br>Incomplete - # 28: Accident Nr and date must appear on the prescription printout
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/28
 * <br>
 * <br>Revision 1.1.2.11  2007/01/11 13:41:06  heinemann
 * <br>Complete - # 21: Context Menu -> create new prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/21
 * <br>
 * <br>Revision 1.1.2.10  2007/01/09 09:42:42  heinemann
 * <br>Complete - # 30: Make prescription editor fullscreen
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/30
 * <br>
 * <br>hidden feature.
 * <br>Click on the tab and it will open as a dialog
 * <br>
 * <br>Revision 1.1.2.9  2007/01/04 13:51:36  heinemann
 * <br>The great space cleaning lady has done a big bunch of refactoring
 * <br>
 * <br>Revision 1.1.2.8  2007/01/03 15:48:12  heinemann
 * <br>prescription was lost, when printing was aborted
 * <br>
 * <br>Revision 1.1.2.7  2006/12/28 15:47:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.6  2006/12/28 10:32:26  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.1.2.5  2006/12/22 07:48:08  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.4  2006/12/21 14:26:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.3  2006/12/19 14:53:05  heinemann
 * <br>printing etc
 * <br>
 * <br>Revision 1.1.2.2  2006/12/15 15:59:11  heinemann
 * <br>presc
 * <br>
 * <br>Revision 1.1.2.1  2006/12/14 09:34:01  heinemann
 * <br>many changes
 * <br>
 */
public class PrescriptionTab extends GECAMedTab {

	/* **********************************************************
	 * Class Members
	 */
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;


	public EditorControler editorControler;

	private AntecedentPrescriptionControler antecedentControler;

	private TemplateControler templateControler;


	private CellConstraints cc;


	private ArrayList<JToggleButton> buttons;


	private IncidentControler incidentControler;


	private JPanel mainPanel;


	private JPanel splitPanel;


	public static List<String> TYPES;
	/* ----------------------------------------------------------
	 * End of Class Members
	 * **********************************************************/

	/**
	 * @param incidentControler
	 */
	public PrescriptionTab(IncidentControler incidentControler) {
		/* ====================================================== */

		Translatrix.addBundle("lu.tudor.santec.gecamed.prescription.gui.resources.Translatrix");

		this.incidentControler = incidentControler;

		editorControler 	= new EditorControler(incidentControler);
		antecedentControler = new AntecedentPrescriptionControler(this);
		templateControler 	= new TemplateControler();


		templateControler.addTemplateReceiver(editorControler);

		this.setTitle(Translatrix.getTranslationString("prescription.name"));


		/* ====================================================== */


	    	TYPES = new ArrayList<String>();

	    	// init the type list
	    	TYPES.add(PrescriptionType.MEDICINE);
	    	TYPES.add(PrescriptionType.RADIOGRAPHY);
	    	TYPES.add(PrescriptionType.CERIFICATS);
	    	TYPES.add(PrescriptionType.PHYSIOTHERAPY);
	    	TYPES.add(PrescriptionType.NURSING);
	    	TYPES.add(PrescriptionType.TRANSFERALS);
	    	TYPES.add(PrescriptionType.BIOLOGY);




		initPanel();

		initButtonActions();

		// first click on button1
		switchType(PrescriptionType.MEDICINE);
		// try to load prescription, that might be attached to the incident
		try {
			editorControler.loadPrescriptions(incidentControler.getIncident().getId());
		} catch (Exception e) {
			// TODO: handle exception
		}

		/* ====================================================== */
	}


	/* ***********************************************************
	 * Methods
	 */




	/**
	 * Opens the view in a dialog in fullscreen
	 */
	public void triggerFullscreen() {
		/* ====================================================== */
		Dimension di = new Dimension(this.getPreferredSize());

		JDialog d = new JDialog(MainFrame.getInstance(), true);
		this.remove(mainPanel);
		this.validate();
		this.updateUI();
		d.setLayout(new BorderLayout());
		d.add(mainPanel);
		d.pack();

		this.setPreferredSize(di);

		MainFrame.showDialogCentered(d);
//		// on return, push it back to the tabbedpane
		this.add(mainPanel);
		this.validate();
		this.updateUI();
		/* ====================================================== */
	}

	/**
	 *
	 */
	private void initButtonActions() {
		/* ====================================================== */

		// the action for the print button
		GECAMedAction printAction = new GECAMedAction(null,
				"prescription.buttons.print",
				GECAMedModule.getSmallIcon(
						GECAMedIconNames.PRINT),
				KeyEvent.VK_P,
				false, false, false) {

					/**
					 *
					 */
					private static final long serialVersionUID = 1L;

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */
						Incident it = incidentControler.getIncidentForPrescription();
						if (editorControler.printPrescription(it)) {
							// lock the editor

							editorControler.reset();
							antecedentControler.updateListData(it);
						}
						/* ============================================= */
					}
		};
		/* ------------------------------------------------------ */

		editorControler.getPrintButton().setAction(printAction);
		editorControler.getPrintButton().setText("");
		editorControler.getPrintButton().setToolTipText(Translatrix.getTranslationString("prescription.buttons.print"));


//		 an action for the print button
		GECAMedAction templateAction = new GECAMedAction(null,
				"prescription.buttons.templates",
				PrescriptionIcons.getSmallIcon(
						PrescriptionIcons.TEMPLATES),
				KeyEvent.VK_T,
				false, false, false) {

					/**
					 *
					 */
					private static final long serialVersionUID = 1L;

					/* (non-Javadoc)
					 * @see lu.tudor.santec.gecamed.core.gui.GECAMedAction#actionPerformed(java.awt.event.ActionEvent)
					 */
					@Override
					public void actionPerformed(ActionEvent p_Event) {
						/* ============================================= */
						templateControler.showEditor();
						/* ============================================= */
					}
		};
		/* ------------------------------------------------------ */

		editorControler.getTemplateButton().setAction(templateAction);
		editorControler.getTemplateButton().setText("");
		editorControler.getTemplateButton().setToolTipText(Translatrix.getTranslationString("prescription.buttons.templates"));
		/* ====================================================== */
	}



	/**
	 * init the panel
	 */
	private void initPanel() {
		/* ====================================================== */
		this.cc = new CellConstraints();

		this.mainPanel = new JPanel(new FormLayout(
				// cols
				"1dlu," +
				"fill:98dlu," +
				"3dlu," +
				"fill:100dlu:grow," +
				"3dlu",
				// rows
				"3dlu," +
				"fill:pref," +
				"3dlu," +
				"fill:pref:grow," +
				"3dlu"));
		this.setOpaque(false);
		this.mainPanel.setOpaque(false);
		/* ------------------------------------------------------ */
		// a Splitpane for the left column
//		this.splitpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
//
//		splitpane.setLeftComponent(templateControler.getPanel());
//		splitpane.setRightComponent(antecedentControler.getPanel());
//
//		splitpane.setOpaque(false);
//
//		splitpane.setDividerLocation(0.6);
//		splitpane.setDividerSize(8);
//		splitpane.setPreferredSize(
//				new Dimension(80, (int) splitpane.getPreferredSize().getHeight()));
//		/* ------------------------------------------------------ */
//		this.mainPanel.add(splitpane, cc.xy(2, 4));
		/* ------------------------------------------------------ */
		// create a panel for the templates
		this.splitPanel = new JPanel(new FormLayout(
				// cols
				"1dlu,fill:10dlu:grow, 1dlu",
				// rows
				"0dlu, fill:20dlu:grow, 3dlu, fill:50dlu"));
		/* ------------------------------------------------------- */
		this.splitPanel.add(templateControler.getPanel(),   cc.xy(2, 2));
		this.splitPanel.add(antecedentControler.getPanel(), cc.xy(2, 4));
		
		this.splitPanel.setOpaque(false);
		
		this.mainPanel.add(splitPanel, cc.xy(2, 4));
		
		/* ------------------------------------------------------- */
		// the main editor
		this.mainPanel.add(editorControler.getPanel(), cc.xy(4, 4));
		/* ------------------------------------------------------ */
		initToggleButtons();
		/* ------------------------------------------------------ */
		// select the first button
		this.buttons.get(0).doClick();
		this.setLayout(new BorderLayout());
		this.add(mainPanel);

		/* ====================================================== */
	}


	/**
	 * init the togglebutton group to switch the prescription types
	 */
	private void initToggleButtons() {
		/* ============================================= */

		// create an actionListener
		ActionListener toggleActionListener = new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				switchType(e.getActionCommand());
				/* ============================================= */
			}
		};
		/* ------------------------------------------------------ */
//		this.buttonBar = new ButtonBarBuilder();
		ButtonGroup bGroup = new ButtonGroup();
		this.buttons = new ArrayList<JToggleButton>();
		for (String t : TYPES) {
			// create a button
			JToggleButton b = new JToggleButton(
					Translatrix.getTranslationString("prescription.name." +t));
			b.setActionCommand(t);
			b.addActionListener(toggleActionListener);
			b.setFont(GECAMedFonts.BUTTON_FONT);
			b.setMargin(new java.awt.Insets(0, 0, 0, 0));
			bGroup.add(b);
			buttons.add(b);

		}

		/* ------------------------------------------------------ */
		// find the max pref size of the buttons
		int width = 0;
		for (JToggleButton tg : buttons) {
			/* ------------------------------------------------------ */
			if (((int)tg.getPreferredSize().getWidth()) > width)
				width = (int) tg.getPreferredSize().getWidth();
			/* ------------------------------------------------------ */
		}
		/* ------------------------------------------------------ */
		// set the max width for all buttons and add to the panel
//		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JPanel buttonPanel = new JPanel(new GridLayout(0, 4));
		for (JToggleButton tb2 : buttons) {
			/* ------------------------------------------------------ */
			tb2.setPreferredSize(new Dimension(width,
							(int) tb2.getPreferredSize().getHeight()));
			buttonPanel.add(tb2);
			/* ------------------------------------------------------ */
		}

		buttonPanel.setOpaque(false);
		// add buttons to the panel
		this.mainPanel.add(buttonPanel, cc.xywh(2, 2, 3, 1));
		/* ============================================= */
	}


	/**
	 * Switch the current prescription type
	 *
	 * @param type
	 */
	protected void switchType(String type) {
		/* ====================================================== */
		templateControler.switchType(type);
		antecedentControler.switchType(type);
		editorControler.switchType(type);


		/* ====================================================== */
	}


	/**
	 * @param currentPatient
	 */
	public void setPatient(Patient currentPatient) {
		/* ============================================= */
		editorControler.reset();
		editorControler.setPatient(currentPatient);

		antecedentControler.setPatient(currentPatient);

		/* ============================================= */
	}



	/**
	 * Saves modified prescriptions and updates the views
	 * 
	 * @return
	 */
	public boolean savePrescriptionData() {
		/* ============================================= */
		// check if there are any changes!!
		if (!editorControler.isModified())
			return false;
		// save the current prescriptions
		Incident it = incidentControler.getIncidentForPrescription();
		editorControler.saveData(it);
		antecedentControler.updateListData(it);
		return true;
		/* ============================================= */
	}

	/**
	 * Set the current incident
	 * 
	 * @param incident
	 */
	public void setIncident(Incident incident) {
		/* ====================================================== */
		antecedentControler.updateListData(incident);
		/* ====================================================== */
	}


	/* -----------------------------------------------------------
	 * End of Methods
	 * ************************************************************/

}
