package com.agilex.healthcare.schedulingmanager.notification.appointmentrequest;

import com.agilex.messaging.core.MessageHandler;
import com.agilex.messaging.provider.beanstalk.QueueAdapter;
import com.agilex.messaging.provider.beanstalk.Tube;
import com.agilex.messaging.provider.beanstalk.config.QueueAdapterInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;

import com.agilex.messaging.core.MessageHandler;
import com.agilex.messaging.provider.beanstalk.BeanstalkBus;
import com.agilex.messaging.provider.beanstalk.Queue;
import com.agilex.messaging.provider.beanstalk.config.BeanstalkBusInfo;

/**
 * Created with IntelliJ IDEA.
 * User: clarkee
 * Date: 2/25/13
 * Time: 10:36 AM
 * To change this template use File | Settings | File Templates.
 */
public class EmailNotificationWorker implements DisposableBean {
    private final static Log logger = LogFactory.getLog(EmailNotificationWorker.class);
    private HaMessagingConfiguration configuration;
    private BeanstalkBus queue;

    public EmailNotificationWorker(HaMessagingConfiguration configuration, EmailNotificationMessageHandler handler) {
        assert (configuration != null);
        assert (handler != null);
        this.configuration = configuration;

        queue = new BeanstalkBus(new BeanstalkBusInfo(configuration.getQueueName(), configuration));

        if (configuration.isEnabled()) {
            run(handler);
        }
    }

    private void run(MessageHandler<EmailNotificationMessage> handler) {
        queue.subscribe(Queue.createDestination(configuration.getQueueName()), handler);
        try {
            queue.start();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Override
    public void destroy() throws Exception {
        if (configuration.isEnabled()) {
            logger.debug("Stopping queue " + queue.info().name());
            queue.stop();
        }
    }
}
