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

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/22/13
 * Time: 10:42 AM
 * To change this template use File | Settings | File Templates.
 */
public class AppointmentRequestMessageNotificationWorker implements DisposableBean {

    private final static Log logger = LogFactory.getLog(AppointmentRequestMessageNotificationWorker.class);
    private HaMessagingConfiguration configuration;
    private BeanstalkBus queue;

    public AppointmentRequestMessageNotificationWorker(HaMessagingConfiguration configuration, AppointmentRequestMessageCreatedMessageHandler 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<AppointmentRequestMessageCreatedMessage> 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 QueueAdapter " + queue.info().name());
            queue.stop();
        }
    }
    
}
