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

import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.table.AbstractTableModel;

import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Insurance;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.PatientStub;
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.utils.SettingConstants;
import lu.tudor.santec.i18n.Translatrix;

public class PatientStubListTableModel extends AbstractTableModel
{
	// ~ Static fields/initializers =========================================
	private static final long			serialVersionUID	= 1L;
	
	// ~ Instance fields ====================================================
	
	protected Class<?>[]				columnClasses		= new Class[] { 
			String.class, 
			String.class, 
			String.class, 
			String.class, 
			String.class, 
			String.class, 
			String.class,
			String.class, 
			String.class,
			String.class,
			String.class 
			};
	
	protected String[]					columnNames			= { /* "eSante", */ 
			Translatrix.getTranslationString("pm.socialNumber"), 
			Translatrix.getTranslationString("pm.lastName"), 
			Translatrix.getTranslationString("pm.maidenName"), 
			Translatrix.getTranslationString("pm.firstName"),
			Translatrix.getTranslationString("pm.gender"), 
			Translatrix.getTranslationString("pm.insuranceShort"), 
			Translatrix.getTranslationString("pm.address"), 
			Translatrix.getTranslationString("pm.phone"), 
			Translatrix.getTranslationString("pm.doc"),
			Translatrix.getTranslationString("pm.id"),
			Translatrix.getTranslationString("pm.storage")
	};
	
	protected ArrayList<PatientStub>	patients			= new ArrayList<PatientStub>();
	
	private InsuranceInterface			manager;
	
	private HashMap<Integer, Insurance>	insurances			= new HashMap<Integer, Insurance>();
	
	private HashMap<Integer, Physician>	physician			= new HashMap<Integer, Physician>();
	
	// ~ Constructors =======================================================
	
	public PatientStubListTableModel()
	{
		// retrieve the needed settings
		if (PatientManagerModule.getInstance().administrativeElementsPlugin.getValue(SettingConstants.MAIDEN_CONFIG) != null && ((Boolean) PatientManagerModule.getInstance().administrativeElementsPlugin.getValue(SettingConstants.MAIDEN_CONFIG)))
		{
			
			columnNames[1] = Translatrix.getTranslationString("pm.maidenName");
			columnNames[2] = Translatrix.getTranslationString("pm.familyName");
			
		}
		
		// fetch all insurances
		try
		{
			manager = (InsuranceInterface) ManagerFactory.getRemote(InsuranceBean.class);
			Insurance[] insuranceArray = manager.getAllInsurancesAsArray();
			for (int i = 0; i < insuranceArray.length; i++)
			{
				insurances.put(insuranceArray[i].getId(), insuranceArray[i]);
			}
		}
		catch (Exception e)
		{
			MainFrame.reportServerError(e);
		}
		
		// fetch all Physician
		try
		{
			for (Physician p : GECAMedLists.getListReference(Physician.class))
			{
				physician.put(p.getId(), p);
			}
		}
		catch (Exception e)
		{
			MainFrame.reportServerError(e);
		}
	}
	
	
	/**
	 * set the ArrayList<PatientStub> containing the patients to be shown
	 * 
	 * @param patients
	 */
	public void setPatients(ArrayList<PatientStub> patients)
	{
		this.patients = patients;
//		for (Iterator<PatientStub> iter = patients.iterator(); iter.hasNext();)
//		{
//			PatientStub ps = iter.next();
//			ps.setAddress(mergeDoubleLines(ps.getAddress()));
//			ps.setPhone(mergeDoubleLines(ps.getPhone()));
//		}
		fireTableDataChanged();
	}
	
	
//	private String mergeDoubleLines(String line)
//	{
//		HashSet<String> hs = new HashSet<String>();
//		String[] lines = line.split("\n");
//		for (int i = 0; i < lines.length; i++)
//		{
//			hs.add(lines[i]);
//		}
//		StringBuffer outLine = new StringBuffer();
//		for (Iterator<String> iter = hs.iterator(); iter.hasNext();)
//		{
//			String s = (String) iter.next();
//			if (s.length() > 2)
//			{
//				outLine.append(s);
//				if (iter.hasNext())
//					outLine.append("\n");
//			}
//		}
//		return outLine.toString();
//	}
	
	
	// ~ Methods ============================================================
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#isCellEditable(int, int)
	 */
	public boolean isCellEditable(int row, int column)
	{
		return false;
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getColumnClass(int)
	 */
	public Class<?> getColumnClass(int col)
	{
		return columnClasses[col];
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getColumnCount()
	 */
	public int getColumnCount()
	{
		return columnNames.length;
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getColumnName(int)
	 */
	public String getColumnName(int col)
	{
		return "<html><b>" + columnNames[col];
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getRowCount()
	 */
	public int getRowCount()
	{
		return patients.size();
	}
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getValueAt(int, int)
	 */
	public Object getValueAt(int row, int col)
	{
		if(row < 0 || row >= patients.size())
			return null;
		
		PatientStub patient = patients.get(row);
		
		switch (col)
		{
			case PatientListPanel.COLUMN_SSN:
				return patient.getSSNInfoString();
			case PatientListPanel.COLUMN_SUR_NAME:
				return patient.getSurName();
			case PatientListPanel.COLUMN_BIRTH_NAME:
				return patient.getMaidenName();
			case PatientListPanel.COLUMN_FIRST_NAME:
				return patient.getFirstName();
			case PatientListPanel.COLUMN_GENDER:
				return patient.getGenderAcronym();
			case PatientListPanel.COLUMN_INSURANCE:
				return insurances.get(patient.getInsuranceID());
			case PatientListPanel.COLUMN_ADDRESS:
				return patient.getAddress();
			case PatientListPanel.COLUMN_PHONE:
				return patient.getPhone();
			case PatientListPanel.COLUMN_PHYSICIAN:
				return physician.get(patient.getDoctorID());
			case PatientListPanel.COLUMN_STORAGE:
				return patient.getStorage();
			case PatientListPanel.COLUMN_ID:
				return patient.getId()+"";
			case PatientListPanel.COLUMN_ESANTE:
				return patient.getIdLuxembourg();
			
		}
		return null;
	}
	
	
	/**
	 * returns the internal patient id for the specified row
	 * 
	 * @param row
	 * @return
	 */
	public Integer getPatientIDforRow(int row)
	{
		try
		{
			return (Integer) this.patients.get(row).getId();
		}
		catch (Exception e)
		{
			return -1;
		}
	}
	
	
	/**
	 * returns the row for the specified patient id
	 * 
	 * @param id
	 * @return
	 */
	public int getRowForPatientID(int id)
	{
		for (int i = 0; i < patients.size(); i++)
		{
			if (patients.get(i).getId().equals(id))
				return i;
		}
		return 0;
	}
	
}
