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

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

import javax.swing.table.AbstractTableModel;

import lu.tudor.santec.gecamed.cara.ejb.entity.beans.Study;
import lu.tudor.santec.gecamed.cara.ejb.session.beans.CaraManagerBean;
import lu.tudor.santec.gecamed.cara.ejb.session.interfaces.CaraManagerInterface;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

public class CaraTableModel extends AbstractTableModel {
 	private static final long serialVersionUID = 1L;

 	private CaraManagerInterface manager;

	private static Logger m_Logger = Logger.getLogger ("lu.tudor.santec.gecamed.cara.gui.CaraTableModel");

	SimpleDateFormat df = new SimpleDateFormat ("d MMMM yyyy");
	
	public static final Integer DICOM_MISSING = 0;
	public static final Integer DICOM_NOT_ARRIVED = 1;
	public static final Integer DICOM_OK = 2;
	
	private final static String[] columns = {
		Translatrix.getTranslationString("cara.status"),
		Translatrix.getTranslationString("cara.date"),
		Translatrix.getTranslationString("cara.modality"),
		Translatrix.getTranslationString("cara.studydesc"),
		Translatrix.getTranslationString("cara.radiologist"),
		Translatrix.getTranslationString("cara.hospital"),
		Translatrix.getTranslationString("cara.image"),
		Translatrix.getTranslationString("cara.text")
	};
	
	private final static Class[] columnClasses = {
		String.class,
		String.class,
		String.class,
		String.class,
		String.class,
		String.class,
		Integer.class,
		Boolean.class
	};
 	
	private Vector<Study> elements = new Vector<Study>();

	public CaraTableModel() {
 		
 		manager = (CaraManagerInterface) ManagerFactory.getRemote(CaraManagerBean.class);
 	}

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

	public int getColumnCount() {
		return columns.length;
	}
	
	@Override
	public String getColumnName(int column) {
		return columns[column];
	}

	@Override
	public Class<?> getColumnClass(int col) {
		return columnClasses[col];
	}


	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		
		if (rowIndex == -1) 
			return null;
		
		Study study;
		try {
			study = elements.get(rowIndex);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		switch (columnIndex) {
		case 0:
			return study.getStatus();
		case 1:
			try {
				return df.format(study.getDate());				
			} catch (Exception e) {
				return df.format(new Date());
			}
		case 2:
			return study.getModality();
		case 3:
			try {
				return study.getHospDescription().replaceAll("\\.", ",");				
			} catch (Exception e) {
				return "";
			}
		case 4:
			return study.getResponsiblePhysician();
		case 5:
			return study.getHospital();
		case 6:
			if (study.getDicomIDs() != null && !study.getDicomIDs().equals("")) {
				if (study.getDicomIDs().startsWith("#"))
					return DICOM_NOT_ARRIVED;
				else
					return DICOM_OK;
			}
			return DICOM_MISSING;
		case 7:
			if (study.getReport() != null && !study.getReport().equals("")) {
				return true;
			}
			return false;
		default:
			return "";
		}
	}
	
	public boolean setPatient(Patient p, boolean force) {
		if (p == null)
			this.elements.removeAllElements();
		
		try {
			Vector<Study> tempElements = new Vector<Study>();
			
			tempElements.addAll(manager.getStudies(p.getId()));
			
			for (Iterator iter = tempElements.iterator(); iter.hasNext();) {
				Study study = (Study) iter.next();
				if (! manager.imageExists(study.getDicomIDs())) {
					study.setDicomIDs("#"+study.getDicomIDs());
				}
			}
			
			// compare
			if (! hasChanges(tempElements) && ! force) {
				return false;
			}
			System.out.println("changes");	
			
			this.elements = tempElements;
			
		} catch (Exception e) {
			try {
				m_Logger.info("No CARA Studies for patient " + p.toShortString() + " found!");				
			} catch (Exception e2) {
			}
		}
		fireTableDataChanged();
		return true;
	}
	
	
	private boolean hasChanges(Vector<Study> tempElements) {
		try {
			// check same size
			if (tempElements.size() != elements.size()) {
				System.out.println("size != size");
				return true;
			}
			// check status and images
			for (int i = 0; i < tempElements.size(); i++) {
				Study tempStudy = tempElements.get(i);
				Study study = elements.get(i);
				// compare status
				if (study.getStatus() != null && tempStudy.getStatus() != null) {
					if (! study.getStatus().equals(tempStudy.getStatus())) {
						System.out.println(study.getStatus() + " != " + tempStudy.getStatus());
						return true;
					}
				}
				if (study.getDicomIDs() != null && tempStudy.getDicomIDs() != null) {
					if (! study.getDicomIDs().equals(tempStudy.getDicomIDs())) {
						System.out.println(study.getDicomIDs() + " != " + tempStudy.getDicomIDs());
						return true;
					}
				}
			}
			return false;
		} catch (Exception e) {
			System.out.println("haschanges Exception");
			e.printStackTrace();
			return true;
		}
	}


	public Study getStudy(int row) {
		if (row < 0)
			return null;
		return elements.get(row);
	}

	
}
