package lu.tudor.santec.gecamed.reporting.gui.listing;

import java.util.Vector;

import javax.swing.AbstractListModel;

import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.reporting.ejb.entity.beans.Report;
import lu.tudor.santec.gecamed.reporting.ejb.session.beans.ReportManagerBean;
import lu.tudor.santec.gecamed.reporting.ejb.session.interfaces.ReportManagerInterface;

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

public class ReportListModel extends AbstractListModel
{
	/* ======================================== */
	// 		CONSTANTS
	/* ======================================== */
	
	private static final long	serialVersionUID	= 1L;
	
	
	
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(ReportListModel.class.getName());
	
	private static ReportManagerInterface	manager;
	
	private Vector<Report>	data;
	
	
	
	/* ======================================== */
	// 		CONSTRUCTORS
	/* ======================================== */
	
	public ReportListModel()
	{
		data	= new Vector<Report>();
		refresh();
	}
	
	
	
	/* ======================================== */
	// 		GETTER & SETTER
	/* ======================================== */
	
	public int getSize()
	{
		return data.size();
	}
	
	
	public Report getElementAt (int index)
	{
		return this.data.get(index);
	}
	
	
	public void add (Report report)
	{
		int		index	= 0;
		
		for (Report currentReport : data)
		{
			if (currentReport.compareTo(report) >= 0)
				break;
			
			index++;
		}
		
		this.data.add(index, report);
		fireIntervalAdded(this, index, index);
	}
	
	
	public boolean remove (Report report)
	{
		int		index	= this.data.indexOf(report);
		if (index >= 0)
			 return remove(index) != null;
		else return false;
	}
	
	
	public Report remove (int index)
	{
		Report	removed	= null;
		if (index > 0 && index < getSize())
		{
			this.data.remove(index);
			fireIntervalRemoved(this, index, index);
		}
		return removed;
	}
	
	
	public void refresh()
	{
		try
		{
			this.data.clear();
			this.data.addAll(getManager().getAllReports());
			fireContentsChanged(this, 0, this.data.size());
		}
		catch (Exception e)
		{
			logger.log(Level.ERROR, e.getMessage(), e);
		} 
	}
	
	
	public void refresh (Report report)
	{
		int	index	= data.indexOf(report);
		if (index >= 0)
			fireContentsChanged(this, index, index);
	}
	
	
	
	/* ======================================== */
	// 		HELP METHODS
	/* ======================================== */
	
	private ReportManagerInterface getManager ()
	{
		if (manager == null)
			manager	= (ReportManagerInterface) ManagerFactory.getRemote(ReportManagerBean.class);
		
		return manager;
	}
}
