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

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

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.backup.ejb.session.interfaces.BackupManagerInterface;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.LogManager;
import lu.tudor.santec.gecamed.core.schedulable.GECAMedHeartbeatPoster;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;
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
 * triggers a backup if the backuptime from the settings is reached.
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: BackupSchedulerBean.java,v $
 * <br>Revision 1.19  2013-12-27 18:09:25  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.18  2013-07-15 06:18:36  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.17  2013-01-10 07:57:17  ferring
 * <br>encoding corrected
 * <br>
 * <br>Revision 1.16  2013-01-10 07:22:12  ferring
 * <br>system logs added
 * <br>
 * <br>Revision 1.15  2013-01-09 08:29:18  ferring
 * <br>Errors in auto backup caught
 * <br>
 * <br>Revision 1.14  2012-03-26 06:03:02  ferring
 * <br>translations added
 * <br>
 * <br>Revision 1.13  2012-03-20 14:35:31  ferring
 * <br>Users are notified via GECAMed message, if automatic backup fails
 * <br>
 * <br>Revision 1.12  2012-02-29 14:24:42  ferring
 * <br>formating changed
 * <br>
 * <br>Revision 1.11  2010-10-13 06:52:28  hermen
 * <br>added backup of Letter Templates
 * <br>
 * <br>Revision 1.10  2010-04-08 10:56:40  hermen
 * <br>enhanced logging
 * <br>
 * <br>Revision 1.9  2009-05-12 09:25:59  hermen
 * <br>cleanup
 * <br>
 * <br>Revision 1.8  2008-09-25 09:42:42  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.7  2008-06-10 08:43:05  hermen
 * <br>fixed NPE when reading settings
 * <br>
 * <br>Revision 1.6  2008-05-28 12:02:48  hermen
 * <br>removed stacktrace on parsing empty settings, added enable/disable backup module
 * <br>
 * <br>Revision 1.5  2008-04-15 10:05:32  hermen
 * <br>fixed deleting of old files
 * <br>
 * <br>Revision 1.4  2008-04-15 10:02:23  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2008-04-15 09:59:36  hermen
 * <br>added backup options
 * <br>
 * <br>Revision 1.2  2008-04-14 12:39:17  hermen
 * <br>extended backup to external files
 * <br>
 * <br>Revision 1.1  2008-04-01 08:17:28  hermen
 * <br>updated backup stuff
 * <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 BackupSchedulerBean implements MessageListener
{
	@EJB
	LoginInterface				loginBean;
	
	@EJB
	BackupManagerInterface		backupManager;
	
	@EJB
	LogManager					logManager;
	
	
	private static boolean		isrunning;
	
	/**
	 * static logger for this class
	 */
	private static Logger		logger			= Logger.getLogger(BackupSchedulerBean.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))
				{
					checkBackup();
				}
			}
		}
		catch (Exception p_Exception)
		{
			logger.log(Level.FATAL, "Failed to process received message", p_Exception);
		}
		isrunning = false;
	}
	
	
	/**
	 * retrieves the backup settings and checks if the backup time is now.
	 */
	private void checkBackup()
	{
		// fetch settings
		SettingReader settingReader = loginBean.getAdminSettingsReader();
		try
		{
			Boolean enabled = (Boolean) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "BACKUP_ENABLED");
			if (enabled == null || enabled == false)
				return;
		}
		catch (Exception e)
		{
			logger.log(Level.INFO, "Failed to read backup settings, no backup.... " + e.getMessage());
			return;
		}
		
		String time = (String) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "BACKUP_TIME");
		int hour = Integer.parseInt(time.split(":")[0]);
		int minute = Integer.parseInt(time.split(":")[1]);
		String weekdays = (String) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "BACKUP_WEEKDAYS");
		
		Boolean doDbBackup = (Boolean) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "DO_DB_BACKUP");
		Boolean doFileBakcup = (Boolean) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "DO_FILE_BACKUP");
		Boolean doDicomBakcup = (Boolean) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "DO_DICOM_BACKUP");
		Boolean doTemplateBackup = (Boolean) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "DO_LETTER_TEMPLATE_BACKUP");
		Integer keepBackups = (Integer) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "NUMBER_OF_BACKUPS");
		String usersToNotify = (String) settingReader.getValue("BACKUP_ADMIN_SETTINGS", "NOTIFIED_USERS");
		
		
		// get current date
		Calendar now = new GregorianCalendar();
		
		// check if weekday is right
		String weekday = now.get(Calendar.DAY_OF_WEEK) + "";
		if (weekdays.indexOf(weekday) >= 0)
		{
			// check hour and minute
			if (now.get(Calendar.HOUR_OF_DAY) == hour && now.get(Calendar.MINUTE) == minute)
			{
				backupManager.startAutoBackup(
						doDbBackup == null ? false : doDbBackup.booleanValue(),
						doFileBakcup == null ? false : doFileBakcup.booleanValue(),
						doDicomBakcup == null ? false : doDicomBakcup.booleanValue(),
						doTemplateBackup == null ? false : doTemplateBackup.booleanValue(),
						keepBackups == null ? 10 : keepBackups.intValue(),
						usersToNotify);
			}
		}
	}
	
	
	public static synchronized void notifyBackupStarted ()
	{
		isrunning = true;
	}
	
	
	public static synchronized void notifyBackupFinished ()
	{
		isrunning = false;
	}
}