/*******************************************************************************
 * 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.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.Language;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.MaritalStatus;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.Nationality;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.ListManagerInterface;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.IconFetcher;
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.utils.ImageTools;
import lu.tudor.santec.gecamed.core.gui.widgets.FileChooserPreview;
import lu.tudor.santec.gecamed.core.gui.widgets.IntegerField;
import lu.tudor.santec.gecamed.core.gui.widgets.LimitTextField;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.formeditor.gui.model.ComboBoxElement;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Insurance;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.InsurancePlan;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.PatientFoto;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.InsuranceBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.InsuranceInterface;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
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.Level;
import org.apache.log4j.Logger;

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

/**
 * Panel to display and edit the patients general data, such as 
 * name, gender, language etc...
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 * consultation
 * @version
 * <br>$Log: PatientGeneralDataBottomPanel.java,v $
 * <br>Revision 1.17  2013-12-27 18:07:57  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.16  2013-07-15 06:18:34  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.15  2013-03-12 09:49:06  kutscheid
 * <br>better photo support if the panel is not visible
 * <br>
 * <br>Revision 1.14  2012-04-23 10:52:50  ferring
 * <br>old insurances, that doesn't exist anymore aren't shown in the combo box anymore. Only if they already set as insurance.
 * <br>
 * <br>Revision 1.13  2010-10-19 14:37:13  troth
 * <br>rename class SimpleViewPanel in OverviewPanel
 * <br>
 * <br>Revision 1.12  2010-06-24 15:29:57  hermen
 * <br>Incomplete - # 522: Portrait Format für Patientenbilder
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/522
 * <br>
 * <br>Revision 1.11  2010-06-24 15:15:13  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.10  2010-06-24 14:00:27  hermen
 * <br>Incomplete - # 522: Portrait Format für Patientenbilder
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/522
 * <br>
 * <br>Revision 1.9  2009-10-05 12:22:15  hermen
 * <br>-added marital state cohabit
 * <br>-added option to disable accident-chooser dialog
 * <br>
 * <br>Revision 1.8  2009-10-01 13:49:13  hermen
 * <br>added physician panel to patient
 * <br>select CNS as default for new patient
 * <br>
 * <br>Revision 1.7  2009-05-29 13:51:21  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.6  2009-01-07 08:54:15  hermen
 * <br>small bugfixes
 * <br>
 * <br>Revision 1.5  2009-01-06 14:48:08  hermen
 * <br>small bugfixes
 * <br>
 * <br>Revision 1.4  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.3  2008-06-12 09:04:48  hermen
 * <br>fixed patient foto bug
 * <br>
 * <br>Revision 1.2  2008-04-16 14:24:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-04-15 16:01:03  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.48  2008-03-17 16:21:23  mack
 * <br>Changes required by moving SSNFormatter into core.utils package
 * <br>
 * <br>Revision 1.47  2008-03-14 08:13:23  hermen
 * <br>enhanced focus traversal
 * <br>
 * <br>Revision 1.46  2008-01-21 14:03:27  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public class PatientGeneralDataBottomPanel extends JPanel implements KeyListener, ItemListener, IPatientDataPanel
{
    //~ Static fields/initializers =============================================
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PatientGeneralDataBottomPanel.class.getName());
	
    private static final long serialVersionUID = 1L;

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

    private IntegerField numberofChildren;
    private JComboBox<ComboBoxElement<Language>> language;
    private JComboBox<ComboBoxElement<MaritalStatus>> maritalStatus;
    private JComboBox<ComboBoxElement<Nationality>> nationality;
    private JComboBox<Insurance> insurance;
    private JComboBox<InsurancePlan> complementary;
	private JTextField	complementaryNo;
    private JLabel foto;
    private PatientAdminPanel patientEditPanel;
	private ListManagerInterface manager;
	private boolean listenersActivated = false;
	private Insurance[] 		insuranceArray;
	private InsurancePlan[] 	insurancePlanArray;
	private PatientFoto fotoData;
	private LimitTextField job;
	private CellConstraints cc;
	private JPanel bottomPanel;
	private JButton addPhotoButton;
	private JButton removePhotoButton;
	private Insurance disbandedInsurance;
	
    //~ Constructors ===========================================================
    /**
     * builds a new PatientInfo to show/edit general Patient Data
     */
    public PatientGeneralDataBottomPanel(PatientAdminPanel patientEditPanel)
    {	
    	this.setOpaque(false);
        this.patientEditPanel = patientEditPanel;
        this.buildPanel();
    }

    //~ Methods ================================================================
    
    
    /**
     * Returns a list of the components that should be used in the focus cycle
     * 
     * @return
     */
    public List<Component> getComponentsForFocus() {
    	/* ================================================== */
    	ArrayList<Component> focusList = new ArrayList<Component>();
    	/* ------------------------------------------------------- */
    	focusList.add(insurance);
    	focusList.add(complementary);
    	focusList.add(complementaryNo);
    	focusList.add(maritalStatus);
    	focusList.add(numberofChildren);
    	focusList.add(job);
    	focusList.add(nationality);
    	focusList.add(language);
    	/* ------------------------------------------------------- */
    	
    	return focusList;
		/* ================================================== */
    }
    
    /* (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)
    {
        // row 2
        try {
        	patient.setInsurance((Insurance)this.insurance.getSelectedItem());
		} catch (ClassCastException e) {
		}
        try {
        	patient.setComplementary((InsurancePlan)this.complementary.getSelectedItem());
		} catch (ClassCastException e) {
		}
        
        if (complementaryNo.getText().trim().length() > 0
        		&& isComplementaryChosen())
        {
        	patient.setComplementaryNo(complementaryNo.getText());
        }
        else
        {
        	patient.setComplementaryNo(null);
        }
        
        // row 3
        
        
        patient.setLanguage(language.getSelectedIndex() < 0 ? language.getSelectedItem()+"" : ((ComboBoxElement<Language>)language.getSelectedItem()).getValue().getValue());
        patient.setNationality(nationality.getSelectedIndex() < 0 ? nationality.getSelectedItem() + "" : ((ComboBoxElement<Nationality>)nationality.getSelectedItem()).getValue().getValue());
        
   
        patient.setMaritalStatus(maritalStatus.getSelectedIndex() < 0 ? null : ((ComboBoxElement<MaritalStatus>)maritalStatus.getSelectedItem()).getValue().getValue());
        patient.setChildrenNumber(this.numberofChildren.getValueInteger());

        // foto
        if (this.fotoData != null) {
        	Set<PatientFoto> fotos = new HashSet<PatientFoto>();
        	fotos.add(this.fotoData);
        	patient.setFotos(fotos);
        } else {
        	patient.setFotos(new HashSet<PatientFoto>());
        }

        patient.setJob(job.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)
	{
		Insurance insurance;
		
		this.setEditable(editable);
		
		listenersActivated = false;
		
		if (disbandedInsurance != null)
		{
			this.insurance.removeItem(disbandedInsurance);
			disbandedInsurance = null;
		}
		
		// row 1
		if (patient.isPersistent())
		{
			insurance = patient.getInsurance();
			if (insurance != null && insurance.getDisbanded())
			{
				disbandedInsurance = insurance;
				this.insurance.addItem(insurance);
			}
			this.insurance.setSelectedItem(insurance);
		}
		else
		{
			for (int i = 0; i < this.insurance.getItemCount(); i++)
			{
				if (((Insurance) this.insurance.getItemAt(i)).getAcronym().equals(Insurance.INSURANCE_CNS))
				{
					this.insurance.setSelectedIndex(i);
					break;
				}
			}
		}
		
		
		this.complementary.setSelectedItem(patient.getComplementary());
		this.complementaryNo.setText(patient.getComplementaryNo());
		
		
		int idx = GECAMedGuiUtils.getIndexByDefaultTranslation(language, patient.getLanguage());
		if (idx >= 0) {
			this.language.setSelectedIndex(idx);
		} else {
			this.language.setSelectedItem(patient.getLanguage());
		}
		
		idx = GECAMedGuiUtils.getIndexByDefaultTranslation(nationality, patient.getNationality());
		if (idx >= 0) {
			this.nationality.setSelectedIndex(idx);			
		} else {
			this.nationality.setSelectedItem(patient.getNationality());
		}
		
		
		
		this.maritalStatus.setSelectedIndex(GECAMedGuiUtils.getIndexByDefaultTranslation(maritalStatus, patient.getMaritalStatus()));
		if (patient.getChildrenNumber() != null) {
			this.numberofChildren.setText(patient.getChildrenNumber() + "");			
		} else {
			this.numberofChildren.setText("");
		}
		
		// display the photo
		if (patient.getFotos() != null && patient.getFotos().size() != 0)
		{
			fotoData = patient.getFotos().iterator().next();
			ImageIcon ii = new ImageIcon(fotoData.getData());
			this.setFoto(ii);
		}
		else
		{
			this.fotoData = null;
			this.setFoto(null);
		}
		
		this.job.setText(patient.getJob());
		
		listenersActivated = true;
	}

    /**
     * enables,disables the panel
     * @param editable
     */
    private void setEditable(boolean editable) {
    	/* ================================================== */
    	this.insurance.setEnabled(editable);
    	this.complementary.setEnabled(editable);
    	this.complementaryNo.setEditable(editable && isComplementaryChosen());
    	this.language.setEnabled(editable);
    	this.nationality.setEnabled(editable);
    	this.maritalStatus.setEnabled(editable);
    	this.numberofChildren.setEditable(editable);
    	this.job.setEditable(editable);
    	/* ================================================== */
	}

	private boolean isComplementaryChosen ()
	{
		if (complementary.getSelectedItem() == null
				|| "-".equals(((InsurancePlan)complementary.getSelectedItem()).getName()))
			return false;
		else
			return true;
	}

	/**
     * adds the components to the panel
     */
    private void buildPanel() {
    	/* ================================================== */
        initComponents();
        this.setLayout(new FormLayout("3dlu,fill:pref:grow,3dlu" , "fill:pref,3dlu"));
        this.cc = new CellConstraints();
        
        buildBottomPanel();
       
        this.add(bottomPanel,      cc.xy(2, 1));
        /* ================================================== */
    }
    
    
    
    
    
    /**
     * Build the bottom panel
     */
    private void buildBottomPanel() {
    	/* ================================================== */
    	this.bottomPanel = new JPanel(new FormLayout(
    			// cols
    			"3dlu," +
    			"right:60dlu," +
    			"5dlu," +
    			
    			"fill:70dlu:grow," +
    			"15dlu," + // 
    			"5dlu," + // gap 6
    			
    			"right:pref," + // 
    			"5dlu," +
    			
    			"fill:50dlu:grow," + // children number
    			"fill:20dlu," +
    			"2dlu," + // gap 11
    			
    			"fill:40dlu," +
    			"3dlu," +
    			"pref",
    			
    			// rows
    			"3dlu," + 		// 1
    			"fill:pref," +  // 2
    			"3dlu," + 		// 3
    			"fill:pref," +	// 4
    			"3dlu," +		// 5
    			"fill:pref," +	// 6
    			"3dlu," +		// 7
    			"fill:pref," +	// 8
    			"3dlu" 			// 9
    			));
    	bottomPanel.setOpaque(false);
    	// =====================================================
    	// create the labels
    	JLabel insuranceLabel       = OverviewPanel.createLabel("pm.insurance");
    	JLabel complementaryLabel	= OverviewPanel.createLabel("pm.complementary");
    	JLabel complementaryNoLabel	= OverviewPanel.createLabel("pm.complementaryNo");
    	JLabel maritalLabel     	= OverviewPanel.createLabel("pm.maritalStatus");
    	
    	JLabel childrenLabel   		= OverviewPanel.createLabel("pm.nrOfChildren");
    	JLabel jobLabel    		    = OverviewPanel.createLabel("pm.job");
    	JLabel nationalityLabel		= OverviewPanel.createLabel("pm.nationality");
    	JLabel languageLabel   		= OverviewPanel.createLabel("pm.language");
    	
    	// ===================================================
    	// place the labels and the fields
    	// in the form
    	// ===================================================
    	// first column --> labels
    	bottomPanel.add(insuranceLabel,       cc.xy(2, 2));
    	bottomPanel.add(complementaryLabel,   cc.xy(2, 4));
    	bottomPanel.add(complementaryNoLabel, cc.xy(2, 6));
    	bottomPanel.add(maritalLabel,         cc.xy(2, 8));
    	
    	// second column of labels
    	bottomPanel.add(childrenLabel,        cc.xy(7, 2));
    	bottomPanel.add(jobLabel,             cc.xy(7, 4));
    	bottomPanel.add(nationalityLabel,     cc.xy(7, 6));
    	bottomPanel.add(languageLabel,        cc.xy(7, 8));
    	
    	/* ------------------------------------------------------- */
    	// place the fields
    	// first column
    	bottomPanel.add(this.insurance,       cc.xy(4, 2));
    	bottomPanel.add(this.complementary,   cc.xy(4, 4));
    	bottomPanel.add(this.complementaryNo, cc.xy(4, 6));
    	bottomPanel.add(this.maritalStatus,   cc.xy(4, 8));
    	
    	// right column
    	bottomPanel.add(this.numberofChildren,cc.xy(9, 2));
    	bottomPanel.add(this.job,             cc.xyw(9, 4, 2));
    	
    	bottomPanel.add(this.nationality,     cc.xyw(9, 6, 2));
    	bottomPanel.add(this.language,        cc.xyw(9, 8, 2));
    	
    	bottomPanel.add(this.foto,            cc.xywh(12, 2, 1, 7));
    	bottomPanel.add(addPhotoButton,       cc.xy(14, 6));
    	bottomPanel.add(removePhotoButton,    cc.xy(14, 8));
		/* ================================================== */
    }
    
    /**
     * initializes the Components
     */
    private void initComponents()
    {

		try {
			InsuranceInterface insuranceManager = (InsuranceInterface)
				ManagerFactory.getRemote(InsuranceBean.class);
			insuranceArray = insuranceManager.getPrimaryInsurancesAsArray();
			insurancePlanArray 	= insuranceManager.getAllInsurancePlansAsArray();
	    } catch (Exception e) {
	    	MainFrame.reportServerError(e);
		}
	    /* ------------------------------------------------------- */
	    // create all input elements
        /* ------------------------------------------------------- */
        this.insurance = new JComboBox<Insurance>(this.insuranceArray);
        
        /* ------------------------------------------------------- */
        // FIXME disabled because of ClassCastException
        // AutoCompletion.enable(this.insurance);
        /* ------------------------------------------------------- */
        this.insurance.addItemListener(this);

        this.complementary = new JComboBox<InsurancePlan>(this.insurancePlanArray);
        /* ------------------------------------------------------- */
        // FIXME disabled because of ClassCastException
        // AutoCompletion.enable(this.complementary);
        /* ------------------------------------------------------- */
        this.complementary.addItemListener(this);
        
        complementaryNo = new JTextField();
        complementaryNo.addKeyListener(this);

        this.language = new JComboBox<ComboBoxElement<Language>>(GECAMedGuiUtils.getTranslatedList(Language.class));
        try {
        	this.language.setSelectedIndex(0);
		} catch (Exception e) {}
        this.language.addItemListener(this);
        this.language.setSelectedItem(Language.LUXEMBOURGISH);
        AutoCompletion.enableWithFreeText(this.language);

        this.nationality = new JComboBox<ComboBoxElement<Nationality>>(GECAMedGuiUtils.getTranslatedList(Nationality.class));
        try {
        	this.nationality.setSelectedIndex(0);
		} catch (Exception e) {}
        this.nationality.addItemListener(this);
        this.nationality.setSelectedItem(Nationality.LUXEMBOURGISH);
        AutoCompletion.enableWithFreeText(this.nationality);

        this.maritalStatus = new JComboBox<ComboBoxElement<MaritalStatus>>(GECAMedGuiUtils.getTranslatedList(MaritalStatus.class));
        try {
        	this.maritalStatus.setSelectedIndex(0);
		} catch (Exception e) {}
        this.maritalStatus.addItemListener(this);
        AutoCompletion.enable(this.maritalStatus);
        
        
        this.numberofChildren = new IntegerField();
        this.numberofChildren.addKeyListener(this);

        // ===============================================================
        // Patient Foto
        // ===============================================================
        this.foto = new JLabel();
        foto.addComponentListener(new ComponentListener() {
			
			public void componentShown(ComponentEvent e) {
			}
			
			public void componentResized(ComponentEvent e) {
				if (fotoData != null) {
					ImageIcon icon = new ImageIcon(fotoData.getData());
					setFoto(icon);
				} else {
					setFoto(null);
				}
			}
			
			public void componentMoved(ComponentEvent e) {
			}
			
			public void componentHidden(ComponentEvent e) {
			}
		});
        foto.setHorizontalAlignment(SwingConstants.CENTER);
        this.setFoto(null);
        
        foto.setBorder(BorderFactory.createLineBorder(OverviewPanel.LIGHT_BORDER));
        
        this.addPhotoButton 	= ButtonFactory.createNarrowButton(IconFetcher.getSmallIcon(GECAMedModule.class, GECAMedIconNames.ADD));
        this.addPhotoButton.setToolTipText(Translatrix.getTranslationString("pm.add"));
        this.addPhotoButton.setFocusable(false);
        this.removePhotoButton  = ButtonFactory.createNarrowButton(IconFetcher.getSmallIcon(GECAMedModule.class, GECAMedIconNames.REMOVE));
        this.removePhotoButton.setToolTipText(Translatrix.getTranslationString("pm.delete"));
        this.removePhotoButton.setFocusable(false);
        
        addPhotoButton   .setContentAreaFilled(false);
        removePhotoButton.setContentAreaFilled(false);
        
        addPhotoButton.setFont(   OverviewPanel.LABEL_FONT);
        removePhotoButton.setFont(OverviewPanel.LABEL_FONT);
        
        
        addPhotoButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				loadFoto();
				/* ====================================================== */
			}
        });
        
        removePhotoButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
			    	if (fotoData == null) return;
			    	
				fotoData = null;
				setFoto(null);
				patientEditPanel.setModified(true);
				/* ====================================================== */
			}
        });
        
        // ===============================================================
        
        
        this.job = new LimitTextField(40);
        this.job.addKeyListener(this);
    }

	/* (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) {
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
	 */
	public void itemStateChanged (ItemEvent e)
	{
		if (listenersActivated)
		{
			this.patientEditPanel.setModified(true);
		}
		if (e.getSource() == complementary)
		{
			complementaryNo.setEditable(isComplementaryChosen());
		}
	}


	/**
	 * sets a photo to the patient record
	 * @param icon
	 */
	private void setFoto(ImageIcon icon) {
		try {

		if (icon != null) {
			int labelHeight = foto.getSize().height;
			if(labelHeight == 0) {
				labelHeight = foto.getPreferredSize().height;
			}
			
			this.foto.setIcon(ImageTools.scaleIcon(icon, -1, labelHeight));
		} else {
			 this.foto.setIcon( PatientManagerModule.getIcon(PatientManagerModule.PATIENT_FOTO));
		}
		foto.setOpaque(false);
		} catch (Exception e) {
			logger.log(Level.WARN, "error setting patient Foto " + e.getLocalizedMessage(), e);
		}
	}


	/**
	 * loads a photo from the file system
	 */
	private void loadFoto() {
		try {
            JFileChooser chooser = new JFileChooser();
            chooser.setAccessory(new FileChooserPreview(chooser));
            if (chooser.showOpenDialog(MainFrame.getInstance()) == JFileChooser.APPROVE_OPTION) {
            	File fotoFile = chooser.getSelectedFile();
            	byte[] b = new byte[(int) fotoFile.length()];
            	new FileInputStream(fotoFile).read(b);

            	BufferedImage imageFoto = ImageTools.toBufferedImage(
            			ImageTools.scaleIcon(
            					new ImageIcon(fotoFile.getAbsolutePath()), -1, 400).getImage());

            	ByteArrayOutputStream baos = new ByteArrayOutputStream();
            	ImageIO.write(imageFoto, "png", baos);
            	if (fotoData == null) {
            		fotoData = new PatientFoto();
            	}
            	fotoData.setData(baos.toByteArray());
            	setFoto(new ImageIcon(baos.toByteArray()));
            	patientEditPanel.setModified(true);
            } 

        } catch (Exception e1) {
        }
	}
	
	public boolean isFilledOK() {
	    return true;
	}
}
