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

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import lu.tudor.santec.gecamed.core.ejb.session.interfaces.LogManager;
import lu.tudor.santec.gecamed.core.gui.ModuleManagerPlugin;
import lu.tudor.santec.gecamed.core.schedulable.GECAMedHeartbeatPoster;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;
import lu.tudor.santec.gecamed.waitingroom.ejb.session.interfaces.WaitingroomManager;
import lu.tudor.santec.settings.SettingReader;

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


/**
 * Message driven bean that registeres to the GECAMED Heartbeat JMS Topic and
 * 
 *
 * @author martin.heinemann@tudor.lu
 * 06.05.2008
 * 16:13:11
 *
 *
 * @version
 * <br>$Log: WaitingroomImportSchedulerBean.java,v $
 * <br>Revision 1.9  2013-12-27 18:09:27  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.8  2013-12-05 16:38:30  ferring
 * <br>Throwables catching changed to get more output about errors
 * <br>
 * <br>Revision 1.7  2013-07-15 06:18:39  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.6  2011-11-16 15:52:32  troth
 * <br>code clearup
 * <br>
 * <br>Revision 1.5  2011-10-28 15:11:02  troth
 * <br>fix Ticket #900: Recurrence Appointments are not show in the Waitingroom.
 * <br>
 * <br>Revision 1.4  2010-07-08 08:25:37  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2010-05-12 09:00:15  hermen
 * <br>changed handling and fetching of room-updates.
 * <br>collectAppointments is now called each 5 min by server,
 * <br>rooms are updated by single entry, not by full reload as before.
 * <br>
 * <br>Revision 1.2  2008-09-25 09:43:10  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.1  2008-05-07 14:39:53  heinemann
 * <br>new waitingroom
 * <br>
 *   
 */
@MessageDriven(activationConfig =
{
  @ActivationConfigProperty(propertyName = "destinationType", 	propertyValue="javax.jms.Topic"),
  @ActivationConfigProperty(propertyName = "destination",		    propertyValue=GECAMedHeartbeatPoster.HeartbeatTopic),
  @ActivationConfigProperty(propertyName = "acknowledgeMode", 	propertyValue = "AUTO_ACKNOWLEDGE"),
  @ActivationConfigProperty(propertyName = "maxSession", 		propertyValue = "1")
 })
public class WaitingroomImportSchedulerBean implements MessageListener{

    @EJB
    LoginInterface loginBean;
    
    @EJB
    WaitingroomManager waitingroomManager;
    
    private static int instanceNr;
    

    private static boolean isrunning;
	
	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(WaitingroomImportSchedulerBean.class
			.getName());
	
	
	/* (non-Javadoc)
	 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
	 */
	public void onMessage(Message msg) {
		/* ================================================== */

	    if (isrunning)
		return;
	    
	    isrunning = true;
		try	{
			if (msg instanceof TextMessage) 	{		
				TextMessage textMessage = (TextMessage) msg;
				if (textMessage.getText() == null)
					return;
				if (textMessage.getText().equals(GECAMedHeartbeatPoster.DoMinutely)){
				    // every 5 min....
				    if (new GregorianCalendar().get(Calendar.MINUTE) % 5 == 0)
					doImport();
				}
			}
		}
		catch (Exception p_Exception){
			logger.log(Level.FATAL, "Failed to process received message",p_Exception);
		}
		
	     isrunning = false;
	     
	     /* ================================================== */
	}

	/**
	 * Start the import from appointment in the waitingrooms
	 */
	private void doImport() {
		// fetch settings
		SettingReader settingReader = loginBean.getAdminSettingsReader();
		try {
			String modules = (String) settingReader.getValue("ModuleManager", "EnabledModules");
		
			if (modules != null && !(modules.contains("AgendaModule") && modules.contains("WaitingroomModule"))) {
				// Either Waitingroom or Calendar not active - NO SYNC -> DONE
				logger.debug("Either Waitingroom or Calendar not active - NO SYNC -> DONE");
		    	return;		 
			}
			
		    Boolean enabled = (Boolean) settingReader.getValue("WaitingroomModuleAdminSettings", "AUTO_IMPORT_ENABLED");
		    if (enabled != null && enabled == false) {
		    	// Auto import disabled - NO SYNC -> DONE
		    	logger.debug("Auto import disabled - NO SYNC -> DONE");
		    	return;		    	
		    }
		} catch (Exception e) {
		    logger.log(Level.INFO, "Failed to read waitingroom admin import, no auto import....", e);
		    return;
		}
	    
		Locale locale = null;
		try {
			locale = (Locale) settingReader.getValue("agendaModuleAdminSettings", "CALENDAR_LOCALE");
			if (locale == null)
				locale = Locale.FRANCE;		    
		} catch (Exception e) {
		    logger.log(Level.INFO, "Failed to read agenda admin settings, calendar locale....");
		    return;
		}
		/* ================================================== */
	    try {
		logger.info("WaitingroomImportSchedulerBean: Doing Appointment import");
			waitingroomManager.collectAppointments4Waitingrooms(locale, true);		
	    } catch (Throwable t) {
	    	logger.warn("Failed to import waitingroom entries", t);
	    }
		/* ================================================== */
	}
	
	
	@PostConstruct
	public void postConstruct () {
	    instanceNr++;
	    logger.info("WaitingroomImportSchedulerBean postConstruct instances: " + instanceNr);
	}
	
	
	@PreDestroy
	public void preDestroy () {
	    instanceNr--;
	    logger.info("WaitingroomImportSchedulerBean preDestroy instances: " + instanceNr);
	}

}