/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software 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 along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.patient.gui.administrative;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.JTextField;

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.widgets.HeaderedPanel;
import lu.tudor.santec.gecamed.core.gui.widgets.NamedComponent;
import lu.tudor.santec.gecamed.core.gui.widgets.PhysicianListModel;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.office.ejb.session.beans.OfficeManagerBean;
import lu.tudor.santec.gecamed.office.ejb.session.interfaces.OfficeManagerInterface;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.utils.SettingConstants;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.beans.LoginBean;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

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


/**
 * Panel to display and edit the additional patient data, such as
 * creation and modified date, createsd by and edited by
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: PatientAdditionalInfo.java,v $
 * <br>Revision 1.26  2013-12-27 18:07:58  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.25  2013-07-15 06:18:34  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.24  2013-03-19 16:09:44  troth
 * <br>1. Set default color for Physician.
 * <br>2. Fix Bug that show the wrong physician if patients physician is null in DB.
 * <br>
 * <br>Revision 1.23  2010-11-18 15:15:24  troth
 * <br>Complete - # 739: Behandelnder Arzt �ndert sich nicht mehr automatisch
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/739
 * <br>
 * <br>Revision 1.22  2010-09-30 11:06:55  troth
 * <br>Complete - # 602: Patient/Arzt �ndert automatisch
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/602
 * <br>
 * <br>Revision 1.21  2010-08-19 14:06:29  troth
 * <br>Incomplete - # 602: Patient/Arzt �ndert automatisch
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/602
 * <br>
 * <br>Revision 1.20  2010-08-17 08:27:11  hermen
 * <br>do not change doctor id of patient if another doctor treats the patient.
 * <br>
 * <br>Revision 1.19  2010-03-12 14:13:17  hermen
 * <br>icon cleanup
 * <br>
 * <br>Revision 1.18  2009-05-29 13:51:21  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.17  2009-01-26 13:32:33  hermen
 * <br>added and implemented right PERMISSION_CHANGE_PHYSICIAN which allows/disallows a user to change the current physician
 * <br>
 * <br>Revision 1.16  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.15  2008-04-16 14:24:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.14  2008-01-21 14:03:27  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class PatientAdditionalInfo extends HeaderedPanel implements IPatientDataPanel
{
    //~ Static fields/initializers =============================================

	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PatientAdditionalInfo.class.getName());
    private static final long serialVersionUID = 1L;
    private static final String COLUMNSPACE = "2dlu"; 

    //~ Instance fields ========================================================

    public JTextField creationDate;
    
    public JTextField lastModified;
    
    public JTextField lastModifiedBy;
    
    private final DateFormat df = GECAMedGuiUtils.getDateFormat(false);
	
    private OfficeManagerInterface manager;
	
	private LoginInterface loginManager;
	
	private JComboBox physicianBox;
	
	private PhysicianListModel physicianComboBoxModel;
	
	private PatientAdminPanel patientEditPanel;

    //~ Constructors ===========================================================
    /**
     * builds a new PhoneInfo to show/edit Phone-Data
     *
     * @param mainFrame a reference to the mainFrame of the Program to obtain all child-objects from
     */
    public PatientAdditionalInfo(PatientAdminPanel patientEditPanel)
    {
    	this.setOpaque(false);
    	this.patientEditPanel = patientEditPanel;
    	this.buildPanel();
    }

    //~ Methods ================================================================

    /* (non-Javadoc)
     * @see lu.tudor.santec.gecamed.patient.gui.administrative.IPatientDataPanel#getPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient)
     */
    public void getPatient(Patient patient)
    {
    	boolean automaticAssignment = true;
    	try {
    		automaticAssignment = (Boolean) PatientManagerModule.getInstance().administrativeElementsPlugin.getValue(SettingConstants.ALLOW_AUTOMATIC_DOCTOR_ASSOCIATION);
		} catch (Exception e) {
			logger.warn("Error reading ALLOW_AUTOMATIC_DOCTOR_ASSOCIATION setting");
		}
    	
    	try {
    		if (automaticAssignment)	
    			patient.setDoctorID(((Physician) physicianBox.getSelectedItem()).getId());
    		else
    	    	patient.setDoctorID(((Physician) MainFrame.getCurrentPhysician()).getId());
    		
    	} catch (Exception e) {
			logger.warn("no physician available. Please create one");
    	}
        patient.setLastModification(new Date());
        patient.setModifiedBy(MainFrame.getCurrentUserId());
    }

    /* (non-Javadoc)
     * @see lu.tudor.santec.gecamed.patient.gui.administrative.IPatientDataPanel#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient, boolean)
     */
    public void setPatient(Patient patient, boolean editable)
    {
		try {
			setTreatingPhysician(patient.getDoctorID());
//			if (patient.getDoctorID() != null)
//			{
//				physicianBox.setSelectedItem(manager.getPhysician(patient.getDoctorID()));
//			} else {
//				physicianBox.setSelectedItem("");
//			}
		} catch (Exception e) {
			logger.warn("no physician available. Please create one");
			setTreatingPhysician(null);
		}
    	
        try {
            this.creationDate.setText(df.format(
                    new Date(patient.getCreationDate().getTime())));
        } catch (Exception e) {
            this.creationDate.setText(Translatrix.getTranslationString(
                    "pm.notDefined")); 
        }
        if (patient.getModifiedBy() != null) {
            try {
                this.lastModifiedBy.setText(loginManager.getUser(patient.getModifiedBy()).toString());
            } catch (Exception e1) {
                this.lastModifiedBy.setText(Translatrix.getTranslationString(
                        "pm.notDefined")); 
            }
        } else {
            this.lastModifiedBy.setText(Translatrix.getTranslationString(
                    "pm.notDefined")); 
        }
        try {
            this.lastModified.setText(df.format(
                    patient.getLastModification()));
        } catch (Exception e) {
            this.lastModified.setText(Translatrix.getTranslationString(
                    "pm.notDefined")); 
        }
        // enabled or disable the manual doctor association
        try {
        	if ((Boolean) PatientManagerModule.getInstance().administrativeElementsPlugin.getValue(SettingConstants.ALLOW_MANUAL_DOCTOR_ASSOCIATION))
        		physicianBox.setEnabled(true);	
        	else
        		physicianBox.setEnabled(false);
		} catch (Exception e) {
		}
    }

    /**
     * adds the components to the panel
     */
    private void buildPanel()
    {
	
    	this.setHeader(Translatrix.getTranslationString("pm.additionalInfo")+":");
	
        // initialize components
        initComponents(); 
        
        // build Layout
        String line = ""; 
        for (int i = 1; i <= 4; i++) {
            line = line + "70dlu:grow, " + COLUMNSPACE + ", ";
        }
        FormLayout layout = new FormLayout(line, "pref, " + COLUMNSPACE + "");
        this.setLayout(layout); 
        CellConstraints cc = new CellConstraints();

        // add Labels
        // row 1
        this.add(new NamedComponent(Translatrix.getTranslationString(
                    "pm.doc"), this.physicianBox), cc.xyw(1, 1, 1));
        this.add(new NamedComponent(Translatrix.getTranslationString(
                    "pm.creationDate"), this.creationDate), 
            cc.xyw(3, 1, 1));
        this.add(new NamedComponent(Translatrix.getTranslationString(
                    "pm.modifiedBy"), this.lastModifiedBy), 
            cc.xyw(5, 1, 1));
        this.add(new NamedComponent(Translatrix.getTranslationString(
                    "pm.lastModified"), this.lastModified), 
            cc.xyw(7, 1, 1));
    }

    /**
     * initializes the Components
     */
    @SuppressWarnings("rawtypes")
	private void initComponents()
    {
		// Get the type manager
		manager = (OfficeManagerInterface) ManagerFactory.getRemote(OfficeManagerBean.class);
		loginManager = (LoginInterface) ManagerFactory.getRemote(LoginBean.class);
    	
		//--------------------------
        // create physician combobox
		//--------------------------
		
        // create physician array
//        Physician[] phys = ((OfficeManagerInterface) ManagerFactory.getRemote(OfficeManagerBean.class))
//        		.getAllPhysicians().toArray(new Physician[0]);
//
//        physicianComboBoxModel = new DefaultComboBoxModel(phys);
//		Vector<Physician> physicians = new Vector<Physician>(GECAMedLists.getListReference(Physician.class));
        physicianComboBoxModel = new PhysicianListModel(null);
        physicianBox = new JComboBox(physicianComboBoxModel);
        //physicianBox.setFont(physicianBox.getFont().deriveFont(Font.BOLD,16));
        physicianBox.setOpaque(true);
        physicianBox.setToolTipText(Translatrix.getTranslationString("main.selectCurrentPhysician"));
        
        try {
        	if ((Boolean) PatientManagerModule.getInstance().administrativeElementsPlugin.getValue(SettingConstants.ALLOW_MANUAL_DOCTOR_ASSOCIATION))
        		physicianBox.setEnabled(true);	
        	else
        		physicianBox.setEnabled(false);
		} catch (Exception e) {
		}
        
//        if (physicianComboBoxModel.getSize() > 5)
//            AutoCompletion.enable(physicianBox);

        // ActionListener for the physician combobox
    	physicianBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				patientEditPanel.setModified(true);
			}
		});
        
        if (!GECAMedModule.userHasPermission(MainFrame.PERMISSIONS_CORE, MainFrame.PERMISSION_CHANGE_PHYSICIAN)) {
            this.physicianBox.setEnabled(false);
        }

        // set the initial physician
        // if the current user has a link to a physician, select it
    	for (int i = 1; i < physicianComboBoxModel.getSize(); i++) {
    		if (MainFrame.getCurrentUser().getId().equals(physicianComboBoxModel.getElementAt(i).getUserId())) {
    			// select the physician in the combobox
    			physicianBox.setSelectedItem(physicianComboBoxModel.getElementAt(i));
    			break;
    		}
    	}
        //--------------------------
        
        this.creationDate = new JTextField();
        this.creationDate.setEditable(false);
        this.lastModified = new JTextField();
        this.lastModified.setEditable(false);
        this.lastModifiedBy = new JTextField();
        this.lastModifiedBy.setEditable(false);
    }

	public List<Component> getComponentsForFocus() {
		return new ArrayList<Component>(0);
	}
	
	public boolean isFilledOK() {
	    return true;
	}
    
    private void setTreatingPhysician (Integer physicianId)
    {
    	if (physicianId == null)
    	{
    		// select the current physician
    		Physician	p	= MainFrame.getCurrentPhysician();
    		Integer		id	= (p == null || p.getId() == null) ? Integer.valueOf(0) : p.getId();
    		
    		setTreatingPhysician(id);
    	}
    	else
    	{
    		Physician	p;
    		
    		for (int index = 0; index < physicianComboBoxModel.getSize(); index++)
    		{
    			p = physicianComboBoxModel.getElementAt(index);
    			if (p != null && physicianId.equals(p.getId()))
    			{
    				physicianBox.setSelectedIndex(index);
    				return;
    			}
    		}
    	}
    }
}
