/*******************************************************************************
 * 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
 *******************************************************************************/
/*
 * Author: Johannes Hermen Tudor/Santec
 * Mail: johannes.hermen@tudor.lu
 * Created: Jan 17, 2005
 *
 */
package lu.tudor.santec.gecamed.office.gui.officemanagement;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;

import javax.swing.JPanel;

import lu.tudor.santec.gecamed.address.ejb.entity.beans.AddressType;
import lu.tudor.santec.gecamed.address.gui.widgets.AddressPanel;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Office;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.OfficeAddress;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

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


/**
 * represents a JPanel to show/edit the offices addresses
 *
 * @author Johannes Hermen johannes.hermen
 * 
 * @Version
 * <br>$Log: OfficeAddressPanel.java,v $
 * <br>Revision 1.32  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.31  2013-07-15 06:18:37  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.30  2012-11-30 08:00:59  ferring
 * <br>postal code added to country and to formatter
 * <br>Short patient title corrected and long patient title added
 * <br>
 * <br>Revision 1.29  2009-02-11 14:05:53  hermen
 * <br>added management of sites to the office admin tab
 * <br>
 * <br>Revision 1.28  2008-09-25 09:43:10  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.27  2008-06-30 08:16:45  hermen
 * <br>added address autocompletion by locality
 * <br>
 * <br>Revision 1.26  2008-04-16 14:24:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.25  2008-01-15 13:08:51  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 */
public class OfficeAddressPanel extends JPanel implements KeyListener, ItemListener, PropertyChangeListener 
{
    //~ Static fields/initializers =============================================

	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(OfficeAddressPanel.class
			.getName());
	
    private static final long serialVersionUID = 1L;
    private static final String COLUMNSPACE = "2dlu"; 
    
	private boolean listenersActivated = false;
	
	private OfficeManagementPanel officeManagementPanel;

	private OfficeAddress currentAddress;
	private AddressPanel addressPanel; 


    //~ Constructors ===========================================================
    /**
     */
    public OfficeAddressPanel(OfficeManagementPanel officeManagementPanel)
    {
    	this.setOpaque(false);
        this.officeManagementPanel = officeManagementPanel;
        this.buildPanel();
    }

    //~ Methods ================================================================
    /**
     * saves the Values of all fields to the passed OfficeAddress object
     *
     * @param address the OfficeAddress object to store the values in
     */
    private void getAddress(OfficeAddress address)
    {
    	if (address == null) {
    		address = new OfficeAddress();
    	}
    	try {
    		address.setType(AddressType.PRIVATE);
    	} catch (Exception e) {
    		logger.log(Level.WARN, "setting address type failed" ,e);
		}
    	
    	address.setZip(this.addressPanel.getZip());
    	
    	address.setLocalityId(this.addressPanel.getLocalityID());
        address.setLocality(this.addressPanel.getTfLocality());
    	
        address.setStreetName(this.addressPanel.getStreetName());
        address.setStreetNumber(this.addressPanel.getStreetNumber());
        
        address.setCountry(this.addressPanel.getCountry());
    	
        if (address.getDate() == null) {
        	address.setDate(new Date());
        }
    }

    /**
     * fills the fields of the panel with data from the passed OfficeAddress
     * object.
     *
     * @param address the OfficeAddress object to load the values from
     */
    private void setAddress(OfficeAddress address)
    {
    	listenersActivated = false;
    		 
		this.addressPanel.setZip(address.getZip());
		
		this.addressPanel.setLocalityID(address.getLocalityId());	
		if (address.getLocalityId() == null) {
			this.addressPanel.setLocality(address.getLocality());
		}
		
		this.addressPanel.setStreet(address.getStreetName(), address.getStreetNumber());
    	
		this.addressPanel.setCountry(address.getCountry());

        listenersActivated = true;
    }

    /**
     * adds the components to the panel
     */
    private void buildPanel()
    {
        initComponents();
        // build Layout
        String line = ""; 
        for (int i = 1; i <= 12; i++) {
            line = line + "25dlu:grow, " + COLUMNSPACE + ", "; 
        }
        FormLayout layout = new FormLayout(line,"pref"); 
        this.setLayout(layout);
//        this.setBorder(new GECAMedTitledBorder(Translatrix.getTranslationString(
//                    "pm.address"))); 
        CellConstraints cc = new CellConstraints();
        this.add(this.addressPanel, cc.xyw(1, 1, 24));
    }

    /**
     * initializes the Components
     */
    private void initComponents()
    {    	
    	this.addressPanel = new AddressPanel(false);
    	this.addressPanel.addPropertyChangeListener(this);
    	
    }

	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
	 */
	public void keyTyped(KeyEvent e) {
		this.officeManagementPanel.setUnsavedChanges(true);
	}
	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
	 */
	public void keyPressed(KeyEvent e) {
	}
	/* (non-Javadoc)
	 * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
	 */
	public void keyReleased(KeyEvent e) {
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
	 */
	public void itemStateChanged(ItemEvent e) {
		if (listenersActivated ) {
			this.officeManagementPanel.setUnsavedChanges(true);
			getAddress(currentAddress);
		}
	}
	
	/**
	 * sets the office to the panel
	 * @param office
	 */
	public void setOffice(Office office) {
		Collection<OfficeAddress> c = office.getOfficeAddress();
		if (c == null) {
			c = new ArrayList<OfficeAddress>();
		}
		if (c.size() == 0) {
			c.add(new OfficeAddress());
		}
		this.currentAddress = c.iterator().next();
		this.setAddress(currentAddress);
	}
	
	/**
	 * gets the office from the panel
	 * @param office
	 */
	public void getData(Office office) {
		HashSet<OfficeAddress> addressess  = new HashSet<OfficeAddress>();
		getAddress(currentAddress);
		addressess.add(currentAddress);
		office.setOfficeAddress(addressess);
	}
	
	/* (non-Javadoc)
	 * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
	 */
	public void propertyChange(PropertyChangeEvent evt) {
		if (listenersActivated && evt.getPropertyName().equals(AddressPanel.UNSAVED_CHANGES)) {
			this.officeManagementPanel.setUnsavedChanges(true);
			getAddress(currentAddress);
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.swing.JComponent#setEnabled(boolean)
	 */
	@Override
	public void setEnabled(boolean enabled) {
		listenersActivated = enabled;
		this.addressPanel.setEditable(enabled);
		super.setEnabled(enabled);
	}
	
}
