package digital.laboratory.platform.entrustment.handler;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author gyDeBug
 * @version 1.0
 * @date 2021/3/30 15:41
 * @description:ActiveMq多实例配置。
 */
@Configuration
public class ActiveMqConfigs {

	/**
	 * activqmq 地址 账号密码注入
	 * @param brokerUrl
	 * @param username
	 * @param password
	 * @return
	 */
	@Bean(name = "activeMQConnectionFactory")
	public ActiveMQConnectionFactory activeMQConnectionFactory(
			@Value("${config.activemq.brokerUrl}") String brokerUrl,
			@Value("${config.activemq.user}") String username,
			@Value("${config.activemq.password}") String password) {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
		factory.setBrokerURL( brokerUrl );
		factory.setUserName( username );
		factory.setPassword( password );
		factory.setTrustedPackages(new ArrayList(Arrays.asList(
				("digital.laboratory.platform.common.core.util," +
						"digital.laboratory.platform.common.core.entity," +
						"java.time," +
						"java.time.chrono," +
						"java.io," +
						"java.lang"
				).split(","))));
		return factory;
	}

	/**
	 * JmsTemplate生成
	 *
	 * @param connectionFactory
	 * @param pubSubDmain
	 * @return
	 */
	@Bean(name = "activeMQJmsTemplate")
	public JmsTemplate activeMQJmsTemplate(
			@Qualifier("activeMQConnectionFactory") ActiveMQConnectionFactory connectionFactory,
			@Value("${config.activemq.pub-sub-domain}") boolean pubSubDmain) {
		JmsTemplate jmsTemplate = new JmsTemplate( connectionFactory );
		jmsTemplate.setPubSubDomain( pubSubDmain );
		return jmsTemplate;
	}

	/**
	 * JmsListener工厂生成
	 *
	 * @param connectionFactory
	 * @param pubSubDmain
	 * @return
	 */
	@Bean(name = "activeMQJmsListenerContainerFactory")
	public JmsListenerContainerFactory activeMQJmsListenerContainerFactory(
			@Qualifier("activeMQConnectionFactory") ActiveMQConnectionFactory connectionFactory,
			@Value("${config.activemq.pub-sub-domain}") boolean pubSubDmain) {
		DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
		factory.setConnectionFactory( connectionFactory );
		factory.setPubSubDomain( pubSubDmain );
		return factory;
	}

}
