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

import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.table.AbstractTableModel;

import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Antecedents;
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.gecamed.usermanagement.ejb.session.beans.LoginBean;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;

import org.apache.log4j.Logger;

/**
 * Table model for the antecedents table.
 * 
 * 
 * @author martin.heinemann@tudor.lu
 * 21.01.2008
 * 15:27:09
 *
 *
 * @version
 * <br>$Log: AntecedentsTableModel.java,v $
 * <br>Revision 1.14  2013-12-27 18:09:27  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.13  2013-07-15 06:18:39  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.12  2010-03-23 15:14:28  troth
 * <br>Redesign of the patient view history -
 * <br>Update method deleteAntecedent and addAntecedents
 * <br>
 * <br>Revision 1.11  2009-06-30 12:24:56  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.10  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.9  2008-07-04 15:49:32  heinemann
 * <br>omplete - # 134: Antecedents cacher
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/134
 * <br>
 * <br>Revision 1.8  2008-01-22 13:51:51  heinemann
 * <br>code cleanup and java doc
 * <br>
 *   
 */
public class AntecedentsTableModel extends AbstractTableModel {
	
	private static final long serialVersionUID = 1L;
 	 	
 	public static final int COL_MAIN = 0;
 	
 	public static final int COL_LOCK = 1;
 	
 	private HistoryManager manager;

	private LoginInterface loginManager;

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

	private Vector<Antecedents> elements = new Vector<Antecedents>();

	private Patient patient;

	private DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT );

 	/**
 	 * 
 	 */
 	public AntecedentsTableModel() {
 		/* ================================================== */
 		try {
 			/* ------------------------------------------------------- */
 			manager = (HistoryManager) ManagerFactory.getRemote(HistoryManagerBean.class);
 			loginManager = (LoginInterface) ManagerFactory.getRemote(LoginBean.class);
 			/* ------------------------------------------------------- */
		}
 		catch (Exception p_Exception) {
 			m_Logger.warn(p_Exception.getLocalizedMessage());
 		}
 		/* ================================================== */
 	}

	public int getRowCount() {
		return elements.size()*2;
	}

	public int getColumnCount() {
		/* ================================================== */
		return 2;
		/* ================================================== */
	}

	@Override
	public String getColumnName(int column) {
		/* ================================================== */
		return "";
		/* ================================================== */
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		/* ================================================== */
		if (columnIndex == COL_MAIN) {
			if (rowIndex%2 == 0) return true;
	
			Antecedents ant = elements.get(rowIndex/2);
			if (ant.getShortcut() == null || ant.getShortcut().equals(""))
				return false;
			
			return true;
		}
		// for locking antecedents
		if (columnIndex == COL_LOCK) {
			/* ------------------------------------------------------- */
			if (rowIndex%2 == 0) return true;
			/* ------------------------------------------------------- */
		}
		return false;
		/* ================================================== */
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		/* ================================================== */
		if (columnIndex == COL_MAIN) {
			/* ------------------------------------------------------- */
	
			if (rowIndex < 0 ) return "";
	
			Antecedents ant = elements.get(rowIndex/2);
			if (rowIndex%2 == 0) {
				return ant.getShortcut();
			}
			String  s = ant.getDescription();
			return  s;
			/* ------------------------------------------------------- */
		} 
		if (columnIndex == COL_LOCK) {
			/* ------------------------------------------------------- */
			if (rowIndex < 0 ) return "";
			
			Antecedents ant = elements.get(rowIndex/2);
			
			if (rowIndex%2 == 0) {
				return ant.getLockedBy();
			}
			return "";
			/* ------------------------------------------------------- */
		}
		return "";
		/* ================================================== */
	}

	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		/* ================================================== */
	    try {
		if (columnIndex == COL_MAIN) {
		    /* ------------------------------------------------------- */
		    Antecedents ant = elements.get(rowIndex/2);
		    
		    if (rowIndex%2 == 0) {
			ant.setShortcut((String)aValue);
		    } else {
			ant.setDescription((String) aValue);
		    }
		    try {
			if (!ant.isPersistent()) {
			    ant.setPatientId(patient.getId());
			    ant.setCreated(new Date());
			    ant.setCreatedBy(GECAMedModule.getCurrentUser().getId());
			}
			ant = manager.saveAntecedents(ant);
			elements.set(rowIndex/2, ant);
			fireTableCellUpdated(rowIndex, columnIndex);
		    } catch (Exception e) {
			e.printStackTrace();
		    }
		    /* ------------------------------------------------------- */
		}
		if (columnIndex == COL_LOCK) {
		    /* ------------------------------------------------------- */
		    if (rowIndex%2 == 0) {
			/* ------------------------------------------------------- */
			Antecedents ant = elements.get(rowIndex/2);
			/* ------------------------------------------------------- */
			if (ant.getLockedBy() != null)
			    ant.setLockedBy(null);
			else
			    ant.setLockedBy(MainFrame.getCurrentUserId());
			
			try {
			    if (!ant.isPersistent()) {
				ant.setPatientId(patient.getId());
				ant.setCreated(new Date());
				ant.setCreatedBy(GECAMedModule.getCurrentUser().getId());
			    }
			    ant = manager.saveAntecedents(ant);
			    elements.set(rowIndex/2, ant);
			    fireTableCellUpdated(rowIndex, columnIndex);
			} catch (Exception e) {
			    e.printStackTrace();
			}
			/* ------------------------------------------------------- */
		    }
		    /* ------------------------------------------------------- */
		}
		/* ================================================== */
		
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}


	/**
	 * @param row
	 * @return
	 */
	public Antecedents getAntecedents(int row) {
		/* ================================================== */
		return elements.get(row/2);
		/* ================================================== */
	}

	/**
	 * @param row
	 * @return
	 */
	public String getAntecedentsInfo(int row) {
		/* ================================================== */
		Antecedents ant = elements.get(row/2);
		try {
			return " <b>" + df.format(ant.getCreated()) + " " + loginManager.getUser(ant.getCreatedBy()).getLogin();
		} catch (Exception e) {
		}
		return "";
		/* ================================================== */
	}

	/**
	 * @param a
	 * @param pos
	 */
	public void addAntecedents(Antecedents a , int pos) {
		/* ================================================== */
		elements.add(pos, a);
		fireTableDataChanged();
		/* ================================================== */
	}
		
	/**
	 * @param p
	 */
	public void setPatient(Patient p) {
		/* ================================================== */
		this.patient = p;
		this.elements.removeAllElements();
		try {
			this.elements.addAll(manager.getAntecedentsByPatientID(p.getId()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		fireTableDataChanged();
		/* ================================================== */
	}
	
	public Vector<Antecedents> getAntecedentsList()
	{
		return elements;
	}

	/**
	 * @param selectedRow
	 */
	public void deleteAntecedent(int selectedRow) {
		/* ================================================== */
		Antecedents ant = getAntecedents(selectedRow);
		elements.remove(ant);
			try {
				if (ant.isPersistent())
					manager.deleteAntecedents(ant);
			} catch (Exception e) {
				e.printStackTrace();
			}
			fireTableDataChanged();
		/* ================================================== */
	}
}
