package org.springblade.common.notify.message;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 统一初始化阿里MQ消息消费者
 *
 * @author caiyihua
 */
@Slf4j
//@Configuration
@ConditionalOnProperty(name = "ali.mq.consumer.support.flag", havingValue = "true", matchIfMissing = false)
public class MessageConsumerInitProcessor implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private AliMqConsumer aliMqConsumer;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Map<String, Object> beans = contextRefreshedEvent.getApplicationContext()
                .getBeansWithAnnotation(MessageHandlerAnnotation.class);
        log.info("There are {} message handlers were found!", beans.size());
        Map<String, List<MessageHandlerHolder>> handlerHolderMap = new ConcurrentHashMap<>();
        for (Object bean : beans.values()) {
            if (bean instanceof MessageHandler) {
                log.info("The message handler class name is: {}", bean.getClass().getName());
                String consumerId = ((MessageHandler) bean).getConsumerId();
                String topic = ((MessageHandler) bean).getTopic();
                String tag = ((MessageHandler) bean).getTag();
                boolean isBroadcast = ((MessageHandler) bean).isBroadcast();
                MessageHandlerHolder messageHandlerHolder = new MessageHandlerHolder(consumerId, topic, tag, isBroadcast,
                        (MessageHandler) bean);
                List<MessageHandlerHolder> handlerHolderList = handlerHolderMap.get(consumerId);
                if (handlerHolderList == null) {
                    handlerHolderList = new ArrayList<>();
                    handlerHolderMap.put(consumerId, handlerHolderList);
                }
                handlerHolderList.add(messageHandlerHolder);
            }
        }

        if (handlerHolderMap.isEmpty()) {
            log.info("There is no any message handler found, just ignore the event!");
            return;
        }

        aliMqConsumer.setHandlerHolderMap(handlerHolderMap);
        aliMqConsumer.start();
    }
}
