/*******************************************************************************
 * 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.patient.gui.administrative;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.PhoneType;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.widgets.EMailField;
import lu.tudor.santec.gecamed.core.gui.widgets.HeaderedPanel;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.PatientPhone;
import lu.tudor.santec.gecamed.patient.gui.simpleview.OverviewPanel;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.ButtonFactory;

import org.apache.log4j.Logger;

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

/**
 * Panel to display and edit the patients phone numbers
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: PatientPhoneInfo.java,v $
 * <br>Revision 1.22  2013-12-27 18:07:56  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.21  2010-10-19 14:37:13  troth
 * <br>rename class SimpleViewPanel in OverviewPanel
 * <br>
 * <br>Revision 1.20  2010-03-12 14:13:17  hermen
 * <br>icon cleanup
 * <br>
 * <br>Revision 1.19  2009-05-29 13:51:21  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.18  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.17  2008-05-09 12:25:23  heinemann
 * <br>removed input restrictions from the phone fields.
 * <br>User can enter additonal text to a number now.
 * <br>Like 0035/8734897389 (daughter)
 * <br>
 * <br>Revision 1.16  2008-04-16 14:24:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.15  2008-01-21 14:03:27  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class PatientPhoneInfo extends HeaderedPanel implements KeyListener, IPatientDataPanel
{
    //~ Static fields/initializers =============================================

    private static final long serialVersionUID = 1L;
    
    /**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(PatientPhoneInfo.class.getName());

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

    private EMailField emailAddress;
    private JTextField cellularNumber;
    private JTextField faxNumber;
    private JTextField officeNumber;
    private JTextField phoneNumber;
    HashMap<String, PatientPhone> phones = new HashMap<String, PatientPhone>();
    private PatientAdminPanel patientEditPanel;
	private boolean listenersActivated;
	private JPanel mainPanel;
	private CellConstraints cc;

	private JButton sendMailButton;

    //~ Constructors ===========================================================
    /**
     * builds a new PhoneInfo to show/edit Phone-Data
     */
    public PatientPhoneInfo(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)
     */
    @SuppressWarnings("unchecked")
	public void getPatient(Patient patient) {
    	List<PatientPhone> phoneList = new ArrayList<PatientPhone>();
    	
    	if (!this.phoneNumber.getText().equals("") )  {
    		PatientPhone p = new PatientPhone();
    		p.setType(PhoneType.HOME);
    		p.setNumber(this.phoneNumber.getText());
        	phoneList.add(p);	
    	}
    	
    	if (!this.cellularNumber.getText().equals("") )  {
    		PatientPhone p = new PatientPhone();
    		p.setType(PhoneType.MOBILE);
    		p.setNumber(this.cellularNumber.getText());
        	phoneList.add(p);	
    	}
    	
    	if (!this.officeNumber.getText().equals("") )  {
    		PatientPhone p = new PatientPhone();
    		p.setType(PhoneType.OFFICE);
    		p.setNumber(this.officeNumber.getText());
        	phoneList.add(p);	
    	}
    	
    	if (!this.faxNumber.getText().equals("") )  {
    		PatientPhone p = new PatientPhone();
    		p.setType(PhoneType.FAX);
    		p.setNumber(this.faxNumber.getText());
        	phoneList.add(p);	
    	}
    	  	
    	patient.setPhones(new HashSet(phoneList));
    	
        patient.setEmail(this.emailAddress.getText());
        
        
    }

    /* (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)
    {
    	
    	setEditable(editable);
    	
    	this.listenersActivated = false;
        // line 1
    	phones.clear();
    	Collection<PatientPhone> phoneList = patient.getPhones();
    	if (phoneList != null) {
    		for (PatientPhone p : phoneList)
    			phones.put(p.getType(), p);
    	}
    		
     	this.phoneNumber.setText(phones.get(PhoneType.HOME) != null ? phones.get(PhoneType.HOME).getNumber() : "");
    	this.cellularNumber.setText(phones.get(PhoneType.MOBILE) != null ? phones.get(PhoneType.MOBILE).getNumber() : "");
    	this.officeNumber.setText(phones.get(PhoneType.OFFICE) != null ? phones.get(PhoneType.OFFICE).getNumber() : "");
    	this.faxNumber.setText(phones.get(PhoneType.FAX) != null ? phones.get(PhoneType.FAX).getNumber() : "");

    	// line 2
        this.emailAddress.setText(patient.getEmail());
        this.listenersActivated = true;
    }

    /**
     * adds the components to the panel
     */
    private void buildPanel() {
    	/* ================================================== */
    	this.setHeader(Translatrix.getTranslationString("pm.contact")+":");
//    	this.setHeaderIcon(PatientManagerModule.getMediumIcon(PatientManagerModule.PHONE));
    	
    	this.enableAlpha(true);
    	this.cc = new CellConstraints();
    	
        initComponents();
        buildViewPanel();
        
        this.setLayout(new BorderLayout());
        this.add(mainPanel, BorderLayout.CENTER);
     
    }


    /**
     * build the gui of the panel
     */
    private void buildViewPanel() {
    	/* ================================================== */
    	
    	this.mainPanel = new JPanel(new FormLayout(
    										// cols
    										"3dlu," +
    										"right:pref," +
    										"5dlu," +
    										"fill:40dlu:grow," +
    	        							"3dlu," +
    	        							"pref," +
    	        							"3dlu," ,
    	        							  // rows
    										"3dlu," +
    										"fill:pref," +
    										"center:5dlu," + // separator
    										"3dlu," +
    										
    										"fill:pref," +
    										"3dlu," +
    										"fill:pref," +
    										"center:5dlu," + // separator
    										"3dlu," +
    										"fill:pref," +
    										"3dlu," +
    										"fill:pref," +
    										"3dlu"));
    	mainPanel.setOpaque(false);
    	/* ------------------------------------------------------- */
    	JLabel telLabel    = OverviewPanel.createLabel("pm.phoneShort");
    	JLabel mobLabel    = OverviewPanel.createLabel("pm.cellular");
    	JLabel officeLabel = OverviewPanel.createLabel("pm.office");
    	JLabel faxLabel    = OverviewPanel.createLabel("pm.fax");
    	JLabel mailLabel   = OverviewPanel.createLabel("pm.mail");
    	
    	/* ------------------------------------------------------- */
    	// place the labels
    	mainPanel.add(telLabel, 		cc.xy(2, 2));
    	mainPanel.add(new JSeparator(), cc.xyw(2, 3, 3));
    	
    	mainPanel.add(mobLabel,         cc.xy(2, 5));
    	mainPanel.add(officeLabel, 		cc.xy(2, 7));
    	
    	mainPanel.add(new JSeparator(), cc.xyw(2, 8, 3));
    	mainPanel.add(faxLabel, 		cc.xy(2, 10));
    	mainPanel.add(mailLabel, 		cc.xy(2, 12));
    	/* ------------------------------------------------------- */
    	// place the fields
    	
    	mainPanel.add(this.phoneNumber,    cc.xyw(4, 2, 3));
    	mainPanel.add(this.cellularNumber, cc.xyw(4, 5, 3));
    	mainPanel.add(this.officeNumber,   cc.xyw(4, 7, 3));
    	mainPanel.add(this.faxNumber,      cc.xyw(4, 10, 3));
    	mainPanel.add(this.emailAddress,   cc.xy(4, 12));
    	mainPanel.add(this.sendMailButton, cc.xy(6, 12));
		/* ================================================== */
    }
    
    
    
    /**
     * initializes the Components
     */
    private void initComponents()
    {  	
    	this.phoneNumber = new JTextField(20);
        this.phoneNumber.addKeyListener(this);
        
        this.cellularNumber = new JTextField(20);
        this.cellularNumber.addKeyListener(this);
        
        this.officeNumber = new JTextField(20);
        this.officeNumber.addKeyListener(this);
        
        this.faxNumber = new JTextField(20);
        this.faxNumber.addKeyListener(this);
        
        this.emailAddress = new EMailField();
        this.emailAddress.addKeyListener(this);
        
        this.sendMailButton = ButtonFactory.createEffectButton(GECAMedModule.getSmallIcon(GECAMedModule.EMAIL));
        sendMailButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					Desktop desktop = Desktop.getDesktop(); 
					desktop.mail(new URI("mailto:" + emailAddress.getText()));
				} catch (Exception e2) {
					logger.warn("Error sending mail to: " + emailAddress.getText() + " " + e2.getMessage());
				}
				
			}
		});
    	
    }

	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
	 */
	public void keyTyped(KeyEvent e) {
		if (listenersActivated )
			this.patientEditPanel.setModified(true);
	}
	public void keyPressed(KeyEvent e) {
	}
	public void keyReleased(KeyEvent e) {
	}
	
	/**
	 * enables the panel to be edited
	 * @param editable
	 */
	private void setEditable(boolean editable) {
		this.phoneNumber.setEditable(editable);
    	this.cellularNumber.setEditable(editable);
    	this.officeNumber.setEditable(editable);
    	this.faxNumber.setEditable(editable);
    	this.emailAddress.setEditable(editable);
	}

	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.gui.administrative.IPatientDataPanel#getComponentsForFocus()
	 */
	public List<Component> getComponentsForFocus() {
		/* ====================================================== */
		List<Component> list = new ArrayList<Component>();
		/* ------------------------------------------------------- */
		list.add(phoneNumber);
		list.add(cellularNumber);
		list.add(officeNumber);
		list.add(faxNumber);
		list.add(emailAddress);
		/* ------------------------------------------------------- */
		return list;
		/* ====================================================== */
	}
	
	public boolean isFilledOK() {
	    return true;
	}
}
