package com.zksy.data.listener;

import com.zksy.data.constant.RabbitMqConstant;
import com.zksy.data.schedule.CollectDataSchedule;
import com.zksy.data.service.IBaseSaveDataInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;

@Configuration
@Slf4j
public class InvokerListener {
    @Autowired
    private CollectDataSchedule collectDataSchedule;
    @Autowired
    private ApplicationContext applicationContext;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMqConstant.INVOKER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = RabbitMqConstant.INVOKER_EXCHANGE_NAME),
            key = RabbitMqConstant.INVOKER_ROUTING_KEY
    ))
    public void listenForInvoker(String targetTableString) {
        Optional.ofNullable(targetTableString).ifPresent(q -> {
            String address = collectDataSchedule.serviceMap.get(targetTableString);
            Object bean = applicationContext.getBean(targetTableString);
            ((IBaseSaveDataInterface) bean).saveDataByUniCode(address);
        });
    }
}
