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

import java.util.Hashtable;

import javax.naming.InitialContext;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.GECAMedEntityBean;
import lu.tudor.santec.gecamed.core.ejb.session.beans.ListManagerBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.ListManagerInterface;
import lu.tudor.santec.gecamed.core.gui.MainFrame;

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

/**
 * Factory to obtain references to SessionBean interfaces.
 * @author martin.heinemann@tudor.lu
 */
public class ManagerFactory {


	/**
	 * Hashtable for remote interfaces 
	 */
	private static Hashtable<String, Object> remoteInterfaceHash = new Hashtable<String, Object>();
	
	/**
	 * Hashtable for local interfaces 
	 */
	private static Hashtable<String, Object> localInterfaceHash = new Hashtable<String, Object>();
	
	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(ManagerFactory.class
			.getName());

	/* *************************************************************
	 * Enter the names of your SessionBean implementations here
	 */
	public static final String VISITMANAGER 			= "VisitManagerBean";
	public static final String DIAGNOSISMANAGER 		= "DiagnosisManagerBean";
	public static final String FINDINGMANAGER 			= "FindingManagerBean";
	public static final String MEASUREMENTMANAGER 		= "MeasurementBean";
	public static final String PRESCRIPTIONMANAGER 		= "PrescriptionManagerBean";
	public static final String PATIENTMANAGER 			= "PatientAdminBean";
	public static final String HOSPITALISATIONMANAGER 	= "HospitalisationBean";
	public static final String ANAMNESISMANAGER 		= "AnamnesisManagerBean";
	public static final String DRUGMANAGER 				= "DrugManagerBean";

	public static final String CEFIPDRUGMANAGER 		= "CefipDrugManagerBean";

	public static final String INCIDENTMANAGER 			= "IncidentManagerBean";
	public static final String INVOICEMANAGER			= "InvoiceBean";
	public static final String MEMOMANAGER 				= "PatientMemoManagerBean";

	public static final String TEMPLATE_MANAGER 		= "TemplateManagerBean";
	public static final String HISTORYMANAGER			= "HistoryManagerBean";
	public static final String LOGINBEAN						= "LoginBean";

	public static final String APPOINTMENTMANAGER		= "AppointmentManagerBean";
	
//	private static final String PREFIX							= "";
	// for EAR file
	public static final String PREFIX							= "GECAMed/";

	/**
	 * Returns a reference to the Remote interface of the specified SessionBean
	 *
	 *	PLEASE USE getRemote(Class managerClass) INSTEAD
	 *
	 * @param the name of the SessionBean
	 * @return the local interface
	 */
	@Deprecated
	public static Object getRemote(String managerName) {
		if (remoteInterfaceHash.get(managerName) == null) {
			try {
				InitialContext ctx = new InitialContext();
//				System.out.println("Lookup: " + PREFIX + managerName+"/remote");
				Object manager =
					ctx.lookup(PREFIX + managerName+"/remote");
				// put
				remoteInterfaceHash.put(managerName, manager);
			} catch (Exception e) {
			    if (MainFrame.getInstance() != null && MainFrame.getInstance().isVisible()) {
			    	MainFrame.reportServerError(e);
			    } else {
			    	logger.log(Level.WARN, "Server error", e);
			    }
			}
		}
		return remoteInterfaceHash.get(managerName);
	}
	
	
	/**
	 * Returns a new instance of that session bean.
	 * 
	 * @param managerClass
	 * @return
	 */
	public static Object getNewInstance(Class<?> managerClass) {
		/* ================================================== */
		try {
			InitialContext ctx = new InitialContext();
			Object manager =
				ctx.lookup(PREFIX + managerClass.getSimpleName()+"/remote");
			// put
			return manager;
		} catch (Exception e) {
			MainFrame.reportServerError(e);
		}
		return null;
		/* ================================================== */
	}
	
	/**
	 * Returns a reference to the Remote interface of the specified SessionBean
	 *
	 * @param the SessionBean
	 * @return the local interface
	 */
	public static Object getRemote(Class<?> managerClass) {
		Object manager	= getRemote(managerClass.getSimpleName());
		
		if (manager == null)
			 throw new GECAMedRemoteException();
		
		return manager;
	}
	
	/**
	 * Returns a reference to the Local interface of the specified SessionBean
	 *
	 * @param the name of the SessionBean
	 * @return the local interface
	 */
	private static Object getLocal(String managerName) {
		if (localInterfaceHash.get(managerName) == null) {
			try {
				InitialContext ctx = new InitialContext();
//				System.out.println("Lookup: " + PREFIX + managerName+"/local");
				Object manager =
					ctx.lookup(PREFIX + managerName+"/local");
				// put
				localInterfaceHash.put(managerName, manager);
			} catch (Exception e) {
				logger.log(
						Level.WARN, 
						"Error getting local interface: " + PREFIX + managerName+"/local",
						e);
			}
		}
		return localInterfaceHash.get(managerName);
	}
	
	/**
	 * Returns a reference to the Local interface of the specified SessionBean
	 *
	 * @param the SessionBean
	 * @return the local interface
	 */
	public static Object getLocal(Class<?> managerClass) {
		return getLocal(managerClass.getSimpleName());
	}

	
	public static Object getStatefulRemote (Class<?> managerClass) 
		{
		Object manager = null;
		try	{
			InitialContext ctx = new InitialContext();
			manager =
					ctx.lookup(PREFIX + managerClass.getSimpleName()+"/remote");
			} 
		catch (Exception e) 
			{
			logger.log(
					Level.WARN, 
					"Error getting remote stateful interface: " + PREFIX + managerClass.getSimpleName()+"/remote",
					e);	
			}
		return manager;
		}
	
	public static Object getStatefulLocal (Class<?> managerClass) 
		{
		Object manager = null;
		try	{
			InitialContext ctx = new InitialContext();
			manager =
					ctx.lookup(PREFIX + managerClass.getSimpleName()+"/local");
			} 
		catch (Exception e) 
			{
			logger.log(
					Level.WARN, 
					"Error getting local stateful interface: " + PREFIX + managerClass.getSimpleName()+"/local",
					e);	
			}
		return manager;
		}
	
	public static <T extends GECAMedEntityBean> T find (Class<T> clazz, Integer id) throws Exception 
	{
		return getListManager().getBean(clazz, id);
	}
	
	
	public static <T extends GECAMedEntityBean> T merge (T bean) throws Exception 
	{
		return getListManager().saveBean(bean);
	}
	
	
	public static <T extends GECAMedEntityBean> void remove (T bean) throws Exception
	{
		getListManager().removeBean(bean);
	}
	
	
	private static ListManagerInterface getListManager() {
		ListManagerInterface manager = null;
		try {
			manager = (ListManagerInterface) ManagerFactory.getRemote(ListManagerBean.class);
		} catch (Throwable outer) {
			logger.error("First attempt to load manager failed, because of following Exception:", outer);

		}
		return manager;
	}

}
