/*******************************************************************************
 * 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.prescription.gui.widgets.editor;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.swing.table.AbstractTableModel;

import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionDrug;
import lu.tudor.santec.gecamed.prescription.ejb.entity.dataclasses.DrugLight;

/**
 * Table model for the drug editor
 *
 *
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: EditorDrugTableModel.java,v $
 * <br>Revision 1.6  2008-10-14 12:18:28  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2008-10-13 09:26:47  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.3  2007/03/12 14:32:10  heinemann
 * <br>Complete - # 46: make printed prescriptions editable
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/46
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:42  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.8  2007/02/08 16:45:11  heinemann
 * <br>many changes
 * <br>
 * <br>Revision 1.1.2.7  2007/01/24 12:48:56  heinemann
 * <br>consultation and prescription update control.
 * <br>Modifications are displayed.
 * <br>And Incidents are not created if nothing has been entered in consultation, accident and prescription
 * <br>
 * <br>Revision 1.1.2.6  2007/01/08 09:51:59  heinemann
 * <br>Incomplete - # 21: Context Menu -> create new prescription
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/21
 * <br>
 * <br>Revision 1.1.2.5  2007/01/04 13:51:37  heinemann
 * <br>The great space cleaning lady has done a big bunch of refactoring
 * <br>
 * <br>Revision 1.1.2.4  2006/12/28 10:32:26  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.1.2.3  2006/12/21 15:56:06  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.2  2006/12/21 14:26:42  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1.2.1  2006/12/19 14:53:05  heinemann
 * <br>printing etc
 * <br>
 */
public class EditorDrugTableModel extends AbstractTableModel {

	private static final long serialVersionUID = 1L;

//	private static Logger logger = Logger.getLogger ("lu.tudor.santec.gecamed.prescription.gui.widgets.editor");

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

	private List<PrescriptionDrug> elements = new ArrayList<PrescriptionDrug>();

 	/**
 	 *
 	 */
 	public EditorDrugTableModel() {
 		/* ====================================================== */
 		// create a first element
 		elements.add(new PrescriptionDrug());
 		fireTableDataChanged();
		/* ====================================================== */
 	}


 	/**
 	 * @return
 	 */
 	public boolean isModified() {
 		/* ====================================================== */
 		if (elements != null) {
 			/* ------------------------------------------------------ */
 			for (PrescriptionDrug d : elements) {
 				if (((!"".equals(d.getName()) && d.getName() != null) || (!"".equals(d.getPosology()) && d.getPosology() != null)))
 					return true;
 			}
 			return false;
 			/* ------------------------------------------------------ */
 		} else
 			return false;
		/* ====================================================== */
 	}


 	/**
 	 * Clear the model
 	 */
 	public void reset() {
 		/* ====================================================== */
 		this.elements.clear();
 		// create a first one
 		this.elements.add(new PrescriptionDrug());
 		fireTableDataChanged();
		/* ====================================================== */
 	}


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

	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getColumnCount()
	 */
	public int getColumnCount() {
		// TODO change to 2, when there are cefip browser and posology chooser
		return 2;
	}

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

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {

		if (columnIndex == 0) {
			if (rowIndex%2 == 0) return true;

			PrescriptionDrug drug = elements.get(rowIndex/2);
			if (drug.getName() == null || drug.getName().equals(""))
				return false;
			else
				return true;
		} else
			return false;
	}

	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getValueAt(int, int)
	 */
	public Object getValueAt(int rowIndex, int columnIndex) {

		PrescriptionDrug drug = elements.get(rowIndex/2);
		if (rowIndex < 0 ) return "";

		if (columnIndex == 0) {

			if (rowIndex%2 == 0) {
				/* ------------------------------------------------------- */
				// create a DrugLight object
				DrugLight dl = new DrugLight();
				dl.setDrugId(drug.getDrugId());
				dl.setName(drug.getName());
				dl.setForm(drug.getForm());
				dl.setListId(drug.getDrugListId());
				return dl;
				/* ------------------------------------------------------- */
			} else {
				//
				String s = drug.getPosology();
				return  s;
			}
		}
		else return "";
	}

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

		PrescriptionDrug drug = elements.get(rowIndex/2);

		if (rowIndex%2 == 0) {
			if (aValue instanceof DrugLight) {
				drug.setName(((DrugLight)aValue).getName());
				drug.setForm(((DrugLight)aValue).getForm());
				drug.setDrugId(((DrugLight)aValue).getDrugId());
				drug.setDrugListId(((DrugLight)aValue).getListId());
			} else {
				drug.setName((String) aValue);
				drug.setDrugId(null);
				drug.setDrugListId(null);
				drug.setForm(null);
			}
			fireTableCellUpdated(rowIndex, columnIndex);
		} else {
			drug.setPosology((String) aValue);
			if (rowIndex == this.getRowCount()-1) {
				// add a new line
				this.addDrug();
				fireTableDataChanged();
			}
		}
	}


	/**
	 * @param row
	 * @return
	 */
	public PrescriptionDrug getDrug(int row) {
		return elements.get(row/2);
	}


	/**
	 * Add a new drug to the list
	 */
	public void addDrug() {
		/* ====================================================== */
		elements.add(new PrescriptionDrug());
		/* ====================================================== */
	}


	/**
	 * @param d
	 * @param pos
	 */
	public void addDrug(PrescriptionDrug d , int pos) {
		// if the first is a dummy, move it to the last position
		deleteEmptyDrug();
		/* ------------------------------------------------------ */
		// add the drug
		elements.add(pos, d);
		/* ------------------------------------------------------ */
		// add an empty one
		this.addDrug();
		fireTableDataChanged();
	}

	public void setNewDrugs(Set<PrescriptionDrug> drugs) {
		/* ====================================================== */
		this.reset();
		elements.clear();
		elements.addAll(drugs);
		elements.add(new PrescriptionDrug());
		fireTableDataChanged();
		/* ====================================================== */
	}

	public void addDrugs(Set<PrescriptionDrug> ds) {
		/* ============================================= */
		deleteEmptyDrug();
		elements.addAll(ds);

		this.addDrug();

		fireTableDataChanged();
		/* ============================================= */
	}

	private void deleteEmptyDrug() {
		/* ====================================================== */
		// if the first is a dummy, remove it
//		int size = elements.size();
//		try {
//		if ("".equals(elements.get(size-1).getName())
//				&& "".equals(elements.get(size-1).getPosology()))
//			elements.remove(size-1);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		/* ------------------------------------------------------- */
		// if the last one is empty, we remove it
		/* ------------------------------------------------------- */
		PrescriptionDrug d = elements.get(elements.size()-1);
		
		if (d.getName() == null || "".equals(d.getName().trim()))
			elements.remove(elements.size()-1);
		/* ------------------------------------------------------ */
		/* ====================================================== */
	}


	/**
	 * @param selectedRow
	 */
	public void deleteDrug(int selectedRow) {
		PrescriptionDrug drug = getDrug(selectedRow);
		elements.remove(drug);
		/* ------------------------------------------------------- */
		// ensure that there is at least one
		/* ------------------------------------------------------- */
		if (elements.size() < 1)
			addDrug();
		/* ------------------------------------------------------- */
		fireTableDataChanged();
	}


	/**
	 *
	 * Get all prescriptionDrugs that have some content
	 *
	 * @return
	 */
	public List<PrescriptionDrug> getAllDrugs() {
		/* ====================================================== */
		// the list to return
		List<PrescriptionDrug> temp = new ArrayList<PrescriptionDrug>();

		// check the drugs
		if (elements != null) {
			for (PrescriptionDrug d : elements) {
				/* ------------------------------------------------------ */
				if (d.getName() != null && !"".equals(d.getName().trim()))
					temp.add(d);
				/* ------------------------------------------------------ */
			}
		}
		return temp;

		/* ====================================================== */
	}


//
//	public boolean isModified() {
//		/* ============================================= */
//		// TODO Auto-generated method stub
//		return this.isModified;
//		/* ============================================= */
//	}
//
//	public void setModified(boolean b) {
//		/* ====================================================== */
//		this.isModified = b;
//		/* ====================================================== */
//	}






}
