/*******************************************************************************
 * 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.office.ejb.session.beans;

import java.util.Collection;
import java.util.Date;

import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.tudor.santec.gecamed.core.ejb.session.beans.GECAMedSessionBean;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Office;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Site;
import lu.tudor.santec.gecamed.office.ejb.session.interfaces.OfficeManagerInterface;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.GecamedInfo;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;

import org.apache.log4j.Level;

/**
 * Session Bean that manages the access to the office and physician EJBs.
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: OfficeManagerBean.java,v $
 * <br>Revision 1.20  2013-07-15 06:18:39  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.19  2009-02-11 14:05:53  hermen
 * <br>added management of sites to the office admin tab
 * <br>
 * <br>Revision 1.18  2009-02-04 16:03:11  hermen
 * <br>added bean and table for site and site_address
 * <br>created GECAMedAddressBean which all addresses should extend
 * <br>
 * <br>Revision 1.17  2008-10-02 15:09:41  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.16  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.15  2008-09-24 09:11:52  heinemann
 * <br>added first run actions to gecamed. will disable all views except the ones of the admin tab for user, office and physician.
 * <br>Tabs are enabled, if an physican was saved.
 * <br>
 * <br>Revision 1.14  2008-08-21 15:45:12  heinemann
 * <br>removed the bogus behaviour when there is no office entry in the database. The fields on the print outs are now left blank. The user gets an information that the office address is missing.
 * <br>
 * <br>Revision 1.13  2008-07-15 08:04:24  hermen
 * <br>added physician address
 * <br>
 * <br>Revision 1.12  2008-07-14 14:33:25  hermen
 * <br>first checkin of the xml2physician mapper
 * <br>
 * <br>Revision 1.11  2008-05-16 15:32:18  heinemann
 * <br>removed appoiuntmentmanager
 * <br>
 * <br>Revision 1.10  2008-04-08 09:52:33  heinemann
 * <br>moved creation of new calendar from OfficeBean to AgendaModule
 * <br>
 * <br>Revision 1.9  2008-03-28 08:51:34  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2008-01-15 13:08:51  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 *
 */
public @Stateless class OfficeManagerBean extends GECAMedSessionBean implements OfficeManagerInterface {

	@PersistenceContext(unitName ="gecam")
	EntityManager em;
	
	@EJB LoginInterface
	loginManager;
	
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.office.ejb.session.interfaces.OfficeManagerInterface#getAllPhysicians()
	 */
//	@SuppressWarnings("unchecked")
//	public List<Physician> getAllPhysicians() {
//		/* ============================================= */
//		List<Physician> result = em.createNamedQuery("findAllPhysician")
//			.getResultList();
//		return result;
//		/* ============================================= */
//	}
	
	 /* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminInterface#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient)
	 */
    @RolesAllowed("gecam")
    public Physician savePhysician(Physician physician)
        throws Exception
    {
        /* ================================================================================== */
        // Throw Exception if right not granted
//    	if (! this.login.userHasPermission("PatientModule.createPatients")) return patient;
        /* ---------------------------------------------------------------------------------- */        
        // set the Physician data
    	physician = em.merge(physician);
    	em.flush();
    	/* ------------------------------------------------------- */
    	// check if this is the first run, we must now set the FIRST_RUN info flag
    	/* ------------------------------------------------------- */
    	GecamedInfo conInfo = null;
		try {
			conInfo = loginManager.getInfo(GecamedInfo.FIRST_RUN);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
    	if (conInfo == null || "false".equals(conInfo.getValue())) {
    		/* ------------------------------------------------------- */
    		conInfo = new GecamedInfo();
    		conInfo.setKey(GecamedInfo.FIRST_RUN);
    		conInfo.setValue("true");
    		conInfo.setDate(new Date());
    		loginManager.setInfo(conInfo);
    		/* ------------------------------------------------------- */
    	}
    	
//    	/* ------------------------------------------------------- */
//    	// create a calendar for the physician
//    	/* ------------------------------------------------------- */
//    	Collection<AgendaCalendar> cals = appointmentManager.getCalendarsByPhysician(physician.getId());
//    	if (cals == null || cals.size() < 1) {
//    		/* ------------------------------------------------------- */
//    		// create a new calendar.
//    		/* ------------------------------------------------------- */
//    		AgendaCalendar ag = new AgendaCalendar();
//    		
//    		ag.setCreated(new Date());
//    		ag.setCreatedBy(loginManager.getCurrentUserID());
//    		
//    		ag.setPhysicianId(physician.getId());
//    		ag.setTitle(physician.toString());
//    		
//    		ag.setColor(physician.getColor());
//    		
//    		ag = appointmentManager.saveCalendar("", ag);
//    		
//    		appointmentManager.sendCalendarUpdateMessage("", AppointmentManager.MSG_ADDED_CALENDAR, ag.getId());
//    		/* ------------------------------------------------------- */
//    	}
        /* ---------------------------------------------------------------------------------- */
        return physician;
        /* ================================================================================== */
    }

    /* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminInterface#getPatient(java.lang.Integer)
	 */
    @RolesAllowed("gecam")
    public Physician getPhysician(Integer physicianID) throws Exception
    {
        /* ================================================================================== */
        // Throw Exception if right not granted
        /* ---------------------------------------------------------------------------------- */
//        if ((patientID == null) || (! this.login.userHasPermission("PatientModule.viewPatients"))) {
//            return null;
//        }
        /* ---------------------------------------------------------------------------------- */
    	Physician pv = em.find(Physician.class, physicianID);
        /* ---------------------------------------------------------------------------------- */
        return pv;
        /* ================================================================================== */
    }

	 /* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminInterface#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient)
	 */
    @RolesAllowed("gecam")
    public Office saveOffice(Office office)
        throws Exception
    {
        /* ================================================================================== */
        // Throw Exception if right not granted
//    	if (! this.login.userHasPermission("PatientModule.createPatients")) return patient;
        /* ---------------------------------------------------------------------------------- */        
        // set the Patients data
    	office = em.merge(office);
        /* ---------------------------------------------------------------------------------- */
        return office;
        /* ================================================================================== */
    }

    /* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminInterface#getPatient(java.lang.Integer)
	 */
    @RolesAllowed("gecam")
    public Office getOffice(Integer officeID) throws Exception
    {
        /* ================================================================================== */
        // Throw Exception if right not granted
        /* ---------------------------------------------------------------------------------- */
//        if ((patientID == null) || (! this.login.userHasPermission("PatientModule.viewPatients"))) {
//            return null;
//        }
        /* ---------------------------------------------------------------------------------- */
//        Office pv = em.find(Office.class, officeID);
    	try {
    		Office pv = (Office) em.createNamedQuery("findAllOffice").setMaxResults(1).getSingleResult();
    		return pv;
    	} catch (Exception e) {
    		/* ------------------------------------------------------- */
    		log(Level.WARN, "No Office Address available!!! Invoices and print outs will be empty in that part.");
    		log(Level.WARN, e.getLocalizedMessage());
    		/* ------------------------------------------------------- */
		}
    	return null;
        /* ---------------------------------------------------------------------------------- */
        /* ================================================================================== */
    }

	public void deletePhysician(Integer physicianID) throws Exception {
        /* ================================================================================== */
        // Throw Exception if right not granted
        /* ---------------------------------------------------------------------------------- */
//        if ((patientID == null) || (! this.login.userHasPermission("PatientModule.viewPatients"))) {
//            return null;
//        }
        /* ---------------------------------------------------------------------------------- */
    	Physician pv = em.find(Physician.class, physicianID);
    	em.remove(pv);
        /* ---------------------------------------------------------------------------------- */
        /* ================================================================================== */
	}
	
	    /* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminInterface#getPatient(java.lang.Integer)
	 */
    @RolesAllowed("gecam")
    public Physician getPhysicianByUCM(String ucm) throws Exception
    {
        /* ---------------------------------------------------------------------------------- */
	Physician pv = null;
	try {
	    pv = (Physician) em.createNamedQuery("getPhysicianByUCMCode")
	    .setParameter("ucmCode", ucm)
	    .setMaxResults(1)
	    .getSingleResult();	    
	} catch (Exception e) {
	}
        /* ---------------------------------------------------------------------------------- */
        return pv;
        /* ================================================================================== */
    }

    @SuppressWarnings("unchecked")
    public Collection<Site> getSites() throws Exception {
	return em.createNamedQuery("findAllSite").getResultList();
    }

    public void deleteSite(Integer siteID) throws Exception {
	em.remove(em.find(Site.class, siteID));
    }

	 /* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminInterface#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient)
	 */
@RolesAllowed("gecam")
public Site saveSite(Site site)
    throws Exception
{
    /* ================================================================================== */
    // Throw Exception if right not granted
//	if (! this.login.userHasPermission("PatientModule.createPatients")) return patient;
    /* ---------------------------------------------------------------------------------- */        
    // set the Sites data
    site = em.merge(site);
    /* ---------------------------------------------------------------------------------- */
    return site;
    /* ================================================================================== */
}
    
    
	
}
