package com.agilex.vamf.missionhealth.message;

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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;

public class EmailNotificationSubscriber implements DisposableBean {
    private final static Log logger = LogFactory.getLog(EmailNotificationSubscriber.class);

    private HaMessagingConfiguration configuration;
    private BeanstalkBus queue;

    public EmailNotificationSubscriber(HaMessagingConfiguration configuration, MessageHandler<EmailNotificationMessage> handler) {
        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 QueueAdapter " + queue.info().name());
            queue.stop();
        }
    }
}

