package com.agilex.vamf.missionhealth.message;

import com.agilex.messaging.core.*;
import com.agilex.messaging.provider.beanstalk.BeanstalkBus;
import com.agilex.messaging.provider.beanstalk.Queue;
import com.agilex.messaging.provider.beanstalk.config.BeanstalkBusInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;

public abstract class EmailMessagePublisher implements DisposableBean {
    protected final static Log logger = LogFactory.getLog(EmailMessagePublisher.class);

    protected HaMessagingConfiguration configuration;
    private BeanstalkBus queue;

    public EmailMessagePublisher(Configuration configuration, String queueName) {
        this.configuration = (HaMessagingConfiguration) configuration;
        assert (configuration != null);

        queue = new BeanstalkBus(new BeanstalkBusInfo(queueName, configuration));
    }

    protected void publishMessage(Message message, String queueName) {
        if (configuration.isEnabled()) {

            try {
                final Destination destination = Queue.createDestination(queueName);
                queue.publish(destination, message);
                logger.debug("Message published");

            } finally {
            }
        } else {
            logger.debug("Message not published due to beanstalk.enabled=false");
        }
    }

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

}