/*******************************************************************************
 * 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.allergy;

import java.util.Date;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Allergens;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Allergies;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.HistoryManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.HistoryManager;
import lu.tudor.santec.i18n.Translatrix;

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

/**
 * Tablemodel to view an edit the patients allergies 
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: AllergyTableModel.java,v $
 * <br>Revision 1.11  2013-12-27 18:09:11  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.10  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.9  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.8  2008-01-21 14:08:58  hermen
 * <br>*** empty log message ***
 * <br>
 *
 */
public class AllergyTableModel extends AbstractTableModel {
 	private static final long serialVersionUID = 1L;

 	private static Logger logger = Logger.getLogger ("lu.tudor.santec.gecamed.patient.gui.history.antecedents");

	private final static String[] columns = {
		Translatrix.getTranslationString("patient.allergy.allergen"),
		Translatrix.getTranslationString("patient.allergy.comment")
	};

	private Vector<Allergies> allergies = new Vector<Allergies>();

	private HistoryManager manager;

	private Patient patient;

	public AllergyTableModel() {
 		try {
 			manager = (HistoryManager) ManagerFactory.getRemote(HistoryManagerBean.class);
 			}
 		catch (Exception p_Exception)
 			{
 			logger.warn(p_Exception.getLocalizedMessage());
 			}
 	}


	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getRowCount()
	 */
	public int getRowCount() {
		return allergies.size();
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getColumnCount()
	 */
	public int getColumnCount() {
		return columns.length;
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.AbstractTableModel#getColumnName(int)
	 */
	@Override
	public String getColumnName(int column) {
		return columns[column];
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.AbstractTableModel#isCellEditable(int, int)
	 */
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return true;
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getValueAt(int, int)
	 */
	public Object getValueAt(int rowIndex, int columnIndex) {
		Allergies all = allergies.get(rowIndex);
		switch (columnIndex) {
		case 0:
			return all.getAllergenName();
		case 1:
			return all.getComment();
		default:
			return "";
		}
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.AbstractTableModel#setValueAt(java.lang.Object, int, int)
	 */
	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		Allergies all = allergies.get(rowIndex);

		switch (columnIndex) {
		case 0:
			all.setAllergenName((String) aValue);
			break;
		case 1:
			all.setComment((String) aValue);
			break;
		default:
			break;
		}

		try {
			if (!all.isPersistent()) {
				all.setPatientId(patient.getId());
				all.setCreated(new Date());
				all.setCreatedBy(GECAMedModule.getCurrentUser().getId());
			}
			all = manager.saveAllergie(all);
			allergies.set(rowIndex, all);
			fireTableDataChanged();
		} catch (Exception e) {
			logger.log(Level.WARN, "saving allergy failed" ,e);
		}

	}

	/**
	 * adds an allergen from the list of existing ones to the patients allergies
	 * @param a
	 */
	public void addAllergen(Allergens a) {
		Allergies all = new Allergies();
		all.setAllergenId(a.getId());
		all.setAllergenName(a.toString());
		all.setCode(a.getCode());
		try {
			if (!all.isPersistent()) {
				all.setPatientId(patient.getId());
				all.setCreated(new Date());
				all.setCreatedBy(GECAMedModule.getCurrentUser().getId());
			}
			all = manager.saveAllergie(all);
			allergies.add(all);
			fireTableDataChanged();
		} catch (Exception e) {
			logger.log(Level.WARN, "saving allergy failed" ,e);
		}
	}

	/**
	 * deletes a patients allergy
	 * @param row
	 */
	public void deleteAllergen(int row) {
		Allergies all = allergies.get(row);
		allergies.remove(all);
			try {
				if (all.isPersistent())
					manager.deleteAllergie(all);
			} catch (Exception e) {
				logger.log(Level.WARN, "deleting allergy failed" ,e);
			}
			fireTableDataChanged();
	}

	/**
	 * sets the patient.
	 * @param p
	 */
	public void setPatient(Patient p) {
		this.patient = p;
		this.allergies.removeAllElements();
		try {
			this.allergies.addAll(manager.getAllergies(p.getId()));
		} catch (Exception e) {
			logger.log(Level.WARN, "updating allergy failed" ,e);
		}
		fireTableDataChanged();
	}

	/**
	 * returns a string representation of the patiens allergies 
	 * to be shown in the important data panel.
	 * @return
	 */
	public String getImportantString() {
		StringBuffer sb = new StringBuffer();
		for (Iterator iter = allergies.iterator(); iter.hasNext();) {
			Allergies element = (Allergies) iter.next();
			sb.append(element.getAllergenName() + " " +  (element.getComment()!=null?element.getComment():"")+  "\n");
		}
		return sb.toString();
	}


}
