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

import com.agilex.messaging.core.Configuration;
import com.agilex.messaging.core.Destination;
import com.agilex.messaging.core.Message;
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.Destination;
import com.agilex.messaging.core.Message;
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: 3/1/13
 * Time: 12:52 PM
 * To change this template use File | Settings | File Templates.
 */
public abstract class MessagingGateway implements DisposableBean {
    protected final static Log logger = LogFactory.getLog(AppointmentRequestMessageNotificationGateway.class);
    protected HaMessagingConfiguration configuration;
    private BeanstalkBus queue;

    public MessagingGateway(HaMessagingConfiguration configuration) {
        this.configuration = configuration;
        assert (configuration != null);
        queue = new BeanstalkBus(new BeanstalkBusInfo(configuration.getQueueName(), configuration));
    }

    protected void publishMessage(Message message) throws MessagePublishException{
        if(configuration.isEnabled()){
            try {
                final Destination destination = Queue.createDestination(configuration.getQueueName());
                logger.debug("Publishing metric message with id : " + message.id() + " to queue: " + destination.toString());
                queue.publish(destination, message);
           }catch (Throwable e){
                throw new MessagePublishException(e);
            }
        }
        else {
            throw new MessagePublishException("The configuration for message.beanstalk.enabled=false");
        }
    }

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