package org.ssssssss.magicapi.rocketmq.starter;


import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.ssssssss.magicapi.core.config.MagicPluginConfiguration;
import org.ssssssss.magicapi.core.model.Plugin;
import org.ssssssss.magicapi.core.web.MagicControllerRegister;
import org.ssssssss.magicapi.rocketmq.product.RocketMqModule;
import org.ssssssss.magicapi.rocketmq.service.DefaultRocketMqService;
import org.ssssssss.magicapi.rocketmq.service.RocketMqInfoMagicResourceStorage;
import org.ssssssss.magicapi.rocketmq.service.RocketMqMagicDynamicRegistry;
import org.ssssssss.magicapi.rocketmq.service.RocketMqService;
import org.ssssssss.magicapi.rocketmq.web.MagicRocketMqController;

/**
 * @author zzy
 */
@Configuration
@EnableConfigurationProperties(MagicRocketMqConfig.class)
public class MagicAPIRocketMqConfiguration implements MagicPluginConfiguration {

    private final MagicRocketMqConfig config;

    @Value("${rocketmq.name-server}")
    private String nameServer;

    public MagicAPIRocketMqConfiguration(MagicRocketMqConfig config) {
        this.config = config;
    }

    @Bean
    @ConditionalOnMissingBean
    public RocketMqInfoMagicResourceStorage rocketMqInfoMagicResourceStorage() {
        return new RocketMqInfoMagicResourceStorage();
    }

    @Bean
    @ConditionalOnMissingBean
    public RocketMqService rocketMqService() {
        return new DefaultRocketMqService();
    }

    @Bean
    @ConditionalOnMissingBean
    public RocketMqMagicDynamicRegistry rocketMqMagicDynamicRegistry(RocketMqInfoMagicResourceStorage rocketMqInfoMagicResourceStorage, RocketMqService rocketMqService) {
        return new RocketMqMagicDynamicRegistry(rocketMqInfoMagicResourceStorage, config.isLog(), rocketMqService, nameServer);
    }

    @Override
    public Plugin plugin() {
        return new Plugin("rocket消息队列", "MagicRocketMq", "magic-rocketmq.1.0.0.iife.js");
    }

    @Override
    public MagicControllerRegister controllerRegister() {
        return (mapping, configuration) -> mapping.registerController(new MagicRocketMqController(configuration));
    }

    /**
     * 注入rocketmq模块
     */
    @Bean
    public RocketMqModule rocketMqFunctions(RocketMQTemplate rocketMQTemplate, RocketMqService rocketMqService) {
        return new RocketMqModule(rocketMQTemplate, rocketMqService);
    }
}
