/*******************************************************************************
 * 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.addressbook.gui.contactpanels;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import lu.tudor.santec.gecamed.addressbook.ejb.entity.beans.Contact;
import lu.tudor.santec.gecamed.addressbook.ejb.session.beans.AddressbookManager;
import lu.tudor.santec.gecamed.addressbook.ejb.session.interfaces.AddressbookInterface;
import lu.tudor.santec.gecamed.addressbook.gui.ContactEditDialog;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.Title;
import lu.tudor.santec.gecamed.core.ejb.session.beans.ListManagerBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.ListManagerInterface;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.AutoCompletion;
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.LimitTextField;
import lu.tudor.santec.gecamed.core.gui.widgets.UCMCodeField;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.UCMCodeFormatter;
import lu.tudor.santec.gecamed.formeditor.gui.model.ComboBoxElement;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.patient.gui.simpleview.OverviewPanel;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * 
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: ContactNamePanel.java,v $
 * <br>Revision 1.8  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.7  2010-10-19 14:37:14  troth
 * <br>rename class SimpleViewPanel in OverviewPanel
 * <br>
 * <br>Revision 1.6  2010-03-19 16:53:41  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2010-03-12 14:12:56  hermen
 * <br>icon cleanup
 * <br>
 * <br>Revision 1.4  2008-12-15 11:03:55  hermen
 * <br>added dr. titles to title combobox
 * <br>
 * <br>Revision 1.3  2008-09-25 09:42:27  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.2  2008-04-30 13:09:51  hermen
 * <br>added sidebar
 * <br>
 * <br>Revision 1.1  2008-04-30 12:18:38  hermen
 * <br>initial checkin of Addressbook module
 * <br>
 *
 */
public class ContactNamePanel extends HeaderedPanel implements KeyListener, IContactDataPanel
{
    //~ Static fields/initializers =============================================

    private static final long serialVersionUID = 1L;
    
    //~ Instance fields ========================================================
    
    private JComboBox type;
    private JTextField name;
    private JTextField firstName;
    private UCMCodeField codeCNS;
    private JComboBox title;
    private JTextField medPres;
    
    private ContactEditDialog contactEditDialog;
	private boolean listenersActivated;
	private JPanel mainPanel;
	private CellConstraints cc;
	
	private String[] titleArray;
	private String[] drTitleArray;
	
	private AddressbookInterface addressbookManager;




    //~ Constructors ===========================================================
    /**
     * builds a new PhoneInfo to show/edit Phone-Data
     */
    public ContactNamePanel(ContactEditDialog contactEditDialog)
    {
    	this.setOpaque(false);
    	this.contactEditDialog = contactEditDialog;
        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 getContact(Contact contact) {
        	contact.setContactType((String)this.type.getSelectedItem());
        	contact.setName(this.name.getText());
        	contact.setNameFirst(this.firstName.getText());
        	contact.setUcmCode((String)this.codeCNS.getValue());
        	contact.setMedpres((this.medPres.getText().trim().length()>0 ? this.medPres.getText() :null));
        	Object t = title.getSelectedItem();
        	if (t != null && t instanceof ComboBoxElement)
        		t = ((ComboBoxElement<?>)title.getSelectedItem()).getValue();
        	contact.setTitle(String.valueOf(t));
    }

    /* (non-Javadoc)
     * @see lu.tudor.santec.gecamed.patient.gui.administrative.IPatientDataPanel#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient, boolean)
     */
    public void setContact(Contact contact, boolean editable)
    {
    	
    	setEditable(editable);
    	
    	this.listenersActivated = false;
    	
    	loadTypes();

     	this.type.setSelectedItem(contact.getContactType());
     	this.name.setText(contact.getName() != null ? contact.getName() : "");
     	this.firstName.setText(contact.getNameFirst() != null ? contact.getNameFirst() : "");
     	this.codeCNS.setValue(contact.getUcmCode() != null ? contact.getUcmCode() : Contact.UCM_DEFAULT);
     	this.medPres.setText(contact.getMedpres() != null ? contact.getMedpres() : "");
     	
     	if (contact.getTitle() != null) {
     		String titleKey = contact.getTitle();
     		ComboBoxModel model = title.getModel();
     		Object elem;
     		
     		int index = 0;
     		for (int i = 0; i < model.getSize(); i++)
     		{
     			elem = model.getElementAt(i);
     			if (elem == null)
     			{
     				continue;
     			}
     			else if (elem instanceof ComboBoxElement)
     			{
     				if (((ComboBoxElement<?>) elem).getValue() == null)
     				{
     					continue;
     				}
     				else if (titleKey.equalsIgnoreCase(String.valueOf(((ComboBoxElement<?>) elem).getValue())))
     				{
     					index = i;
     					break;
     				}
     			}
     			else if (elem instanceof String)
     			{
     				if (titleKey.equalsIgnoreCase((String) elem))
     				{
     					index = i;
     					break;
     				}
     			}
     		}
     		if (index == 0)
     			title.setSelectedItem(contact.getTitle());
     		else
     			title.setSelectedIndex(index);
     	}
     	else
     	{
     		title.setSelectedIndex(0);
     	}
        
        this.listenersActivated = true;
    }

	
	private void loadTypes ()
	{
		this.type.removeAllItems();
		Collection<String> types = addressbookManager.getContactTypes();
		type.addItem("");
		for (Iterator<String> iter = types.iterator(); iter.hasNext();)
		{
			String element = (String) iter.next();
			type.addItem(element);
		}
	}


    /**
     * adds the components to the panel
     */
    private void buildPanel() {
    	/* ================================================== */
    	this.setHeader(Translatrix.getTranslationString("Addressbook.general")+":");
//    	this.setHeaderIcon(IconFetcher.getMediumIcon(AddressbookModule.class, AddressbookModule.ICON_EDIT_CONTACT));
    	
    	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:50dlu," +
    										"5dlu," +
    										
    										"fill:90dlu," +
    										"fill:pref:grow",
    										// rows
    										"3dlu," +
    										"fill:pref," +
    										"center:5dlu," + // separator
    										"3dlu," +
    										
    										"fill:pref," +
    										"3dlu," +
    										"fill:pref," +
    										"center:5dlu," + // separator
    										"3dlu," +
    										"fill:pref," +
    										"3dlu," +
    										"fill:pref," +
    										"3dlu," +
    										"fill:pref," +
    										"3dlu"));
    	mainPanel.setOpaque(false);
    	/* ------------------------------------------------------- */
    	JLabel typeLabel    = OverviewPanel.createLabel("Addressbook.type");
    	JLabel nameLabel    = OverviewPanel.createLabel("Addressbook.name");
    	JLabel firstnameLabel = OverviewPanel.createLabel("Addressbook.firstname");
    	JLabel ucmLabel    = OverviewPanel.createLabel("Addressbook.ucmCode");
    	JLabel titleLabel   = OverviewPanel.createLabel("Addressbook.title");
    	JLabel medPresLabel   = OverviewPanel.createLabel("Addressbook.MedPres");
    	
    	/* ------------------------------------------------------- */
    	// place the labels
    	mainPanel.add(typeLabel, 		cc.xy(2, 2));
    	mainPanel.add(new JSeparator(), cc.xyw(2, 3, 3));
    	
    	mainPanel.add(nameLabel,        cc.xy(2, 5));
    	mainPanel.add(firstnameLabel,	cc.xy(2, 7));
    	
    	mainPanel.add(new JSeparator(), cc.xyw(2, 8, 3));
    	mainPanel.add(titleLabel, 		cc.xy(2, 10));
    	mainPanel.add(ucmLabel, 		cc.xy(2, 12));
    	mainPanel.add(medPresLabel, 	cc.xy(2, 14));
    	/* ------------------------------------------------------- */
    	// place the fields
    	
    	mainPanel.add(this.type,		cc.xy(4, 2));
    	mainPanel.add(this.name,		cc.xy(4, 5));
    	mainPanel.add(this.firstName,	cc.xy(4, 7));
    	mainPanel.add(this.title,		cc.xy(4, 10));
    	mainPanel.add(this.codeCNS,		cc.xy(4, 12));
    	mainPanel.add(this.medPres,		cc.xy(4, 14));
		/* ================================================== */
    }
    
    
    
    /**
     * initializes the Components
     */
    private void initComponents()
	{
		// Get the type manager
		try
		{
			ListManagerInterface manager =
					(ListManagerInterface) ManagerFactory.getRemote(ListManagerBean.class);
			titleArray			= manager.getTitles();
			drTitleArray		= manager.getDrTitles();
			addressbookManager	= (AddressbookInterface) ManagerFactory.getRemote(AddressbookManager.class);
		}
		catch (Exception e)
		{
			MainFrame.reportServerError(e);
		}
		
		
		this.type = new JComboBox();
		this.type.addKeyListener(this);
		AutoCompletion.enableWithFreeText(this.type);
		this.name = new LimitTextField(40);
		this.name.addKeyListener(this);
		this.firstName = new LimitTextField(40);
		this.firstName.addKeyListener(this);
		this.codeCNS = new UCMCodeField(new UCMCodeFormatter());
		this.codeCNS.addKeyListener(this);
		this.codeCNS.getDocument().addDocumentListener(new DocumentListener() {
			public void removeUpdate(DocumentEvent e) {
				changedUpdate(e);
			}
			public void insertUpdate(DocumentEvent e) {
				changedUpdate(e);
			}
			public void changedUpdate(DocumentEvent e) {
				medPres.setEnabled(
						codeCNS.getText() != null && ! codeCNS.getText().equals(Physician.UCM_DEFAULT)
				);
			}
		});
		this.medPres = new LimitTextField(10);

		
		// create all input elements
		List<String> list = new LinkedList<String>();
		String item;
		list.add(0, "");
		for (int i = 0; i < titleArray.length; i++)
		{
			item = titleArray[i];
			if (list.contains(item.trim()))
				continue;
			list.add(item);
		}
		for (int i = 0; i < drTitleArray.length; i++)
		{
			item = drTitleArray[i];
			if (list.contains(item.trim()))
				continue;
			list.add(item);
		}
		
//	String[] arr = al.toArray(new String[0]);
//	this.title = new TranslatedComboBox(Title.class, arr);
		
//	title = new JComboBox(GECAMedGuiUtils.getTranslatedList(Title.class));
		String translationPrefix = Title.class.getSimpleName() + ".";
		title = new JComboBox(GECAMedGuiUtils.getTranslatedList(list, translationPrefix, true));
//		AutoCompletion.enable(title);
		AutoCompletion.enableWithFreeText(title);
		try
		{
			this.title.setSelectedIndex(1);
		}
		catch (Exception e)
		{
		}
		
		Dimension d = name.getPreferredSize();
		type.setPreferredSize(d);
		title.setPreferredSize(d);
		
	}

	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
	 */
	public void keyTyped(KeyEvent e) { 
		if (e.getSource().equals(this.codeCNS)) {
			medPres.setEnabled(codeCNS.getText() != null && ! codeCNS.getText().equals(Physician.UCM_DEFAULT));
		}
//		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.type.setEditable(editable);
        this.name.setEditable(editable);
        this.firstName.setEditable(editable);
        this.codeCNS.setEditable(editable);
        this.title.setEditable(editable);
        this.medPres.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(type);
		list.add(name);
		list.add(firstName);
		list.add(codeCNS);
		list.add(medPres);
		list.add(title);
		/* ------------------------------------------------------- */
		return list;
		/* ====================================================== */
	}
}
