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

import java.util.Date;
import java.util.List;

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

import lu.tudor.santec.gecamed.core.ejb.entity.beans.log.Log;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.log.LogType;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.LogManager;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.MessageSenderInterface;
import lu.tudor.santec.gecamed.core.gui.LoginScreen;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;

/**
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: LogManagerBean.java,v $
 * <br>Revision 1.13  2013-07-15 06:18:36  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.12  2013-01-09 08:29:18  ferring
 * <br>Errors in auto backup caught
 * <br>
 * <br>Revision 1.11  2012-05-25 12:04:24  ferring
 * <br>Filters of logging overview updated
 * <br>
 * <br>Revision 1.10  2011-10-04 10:43:41  troth
 * <br>removed some warnings
 * <br>
 * <br>Revision 1.9  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.8  2008-04-01 11:58:42  hermen
 * <br>added logging
 * <br>
 * <br>Revision 1.7  2007-10-08 15:14:42  mack
 * <br>Removed JMS message send for log entry save.
 * <br>
 * <br>Revision 1.6  2006/11/28 12:17:50  hermen
 * <br>removed sysout's
 * <br>
 * <br>Revision 1.5  2006/11/22 13:00:31  heinemann
 * <br>you shouldn't do that, stefan ;-)
 * <br>
 * <br>Revision 1.4  2006/11/07 08:11:32  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2006/11/06 12:06:18  hermen
 * <br>changed import
 * <br>
 * <br>Revision 1.2  2006/10/25 11:17:15  heinemann
 * <br>improved logging
 * <br>
 * <br>Revision 1.1  2006/10/24 09:18:39  heinemann
 * <br>New Beans for the logging
 * <br>
 */
public @Stateless class LogManagerBean implements LogManager {

//	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
//	private static Logger logger = Logger.getLogger(LogManagerBean.class.getName());
	
	
	/**
	 * The default start position for all result lists of logs
	 */
	private int start = 0;
	/**
	 * The default pagesize of a resultset of log messages
	 */
	private int pagesize = 100;
	
	
	@PersistenceContext(unitName="gecam")
	EntityManager em;
	
	@EJB
	LoginInterface loginBean;
	
	@EJB
    MessageSenderInterface messageLocal;
	
	@Resource
	SessionContext sessionContext;
	
	
	
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.ejb.session.interfaces.LogManager#saveLog(lu.tudor.santec.gecamed.core.ejb.entity.beans.log.Log)
	 */
	public void saveLog (Log log) {
		/* ============================================= */
		if (log != null) 
		{
			/* ------------------------------------------------------ */
			// set the current time
			log.setTime(new Date());
			
			// the user
			try 
			{
				log.setUserId(loginBean.getCurrentUserID());
				log.setUserName(loginBean.getCurrentUserName());
			}
			catch (Exception e)
			{
				log.setUserId(-1);
				log.setUserName("System");
//				logger.log(Level.ERROR, e.getMessage(), e);
			}
			// save
			if (log.isPersistent()) 
				log.setId(null);
			
			em.persist(log);
			/* ------------------------------------------------------ */
			// notify all clients to update their log list.
//			  try {
//                messageLocal.sendLogUpdateMessage();
//            } catch (JMSException e) {
//                e.printStackTrace();
//            }
			/* ------------------------------------------------------ */
		}
		/* ============================================= */
	}
	
	public void createLogMessage(Integer logType, String module, 
			String operation, String message, Long duration) {
		/* ====================================================== */

		// write a new log message
		Log log = new Log();
		log.setTypeId(logType);
		log.setModule(module);
		log.setOperation(operation);
		log.setText(message);
		log.setHost("SERVER");
		log.setDuration(duration);

		saveLog(log);
		/* ====================================================== */
	}


	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.ejb.session.interfaces.LogManager#getLogs(java.lang.Integer, java.lang.Integer)
	 */
	@SuppressWarnings("unchecked")
	@RolesAllowed("gecam")
	public List<Log> getLogs (Integer start, Integer pagesize, Date fromDate, Date toDate, String filter) {
		/* ============================================= */
		// set the startposition
		if (start != null && start > 0)
			this.start = start;
		// set the pagesize
		if (pagesize != null && pagesize > 0)
			this.pagesize = pagesize;
		/* ------------------------------------------------------ */
		StringBuffer buff = new StringBuffer();
		buff.append("SELECT Object(o) FROM Log o");
		buff.append(filter);
		buff.append(" ORDER BY o.time DESC");
		Query q = em.createQuery(buff.toString());
		/* ------------------------------------------------------ */
		// replace the dates
		if (fromDate != null) q.setParameter("fromDate", fromDate);
		if (toDate   != null) q.setParameter("toDate",   toDate);
		
		q.setFirstResult(this.start);
		q.setMaxResults(this.pagesize);
		/* ------------------------------------------------------ */
		List<Log> result = q.getResultList();
		/* ------------------------------------------------------ */
		return result;
		/* ============================================= */
	}


	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.ejb.session.interfaces.LogManager#getLogTypes()
	 */
	@SuppressWarnings("unchecked")
	public List<LogType> getLogTypes () {
		/* ============================================= */
		Query q = em.createQuery("SELECT Object(o) FROM LogType o");
		
		return q.getResultList();
		/* ============================================= */
	}

}
