
package com.mortals.xhx.queue.provider;

import com.mortals.xhx.queue.*;
import com.mortals.xhx.queue.rabbitmq.TbRabbitMqConsumerTemplate;
import com.mortals.xhx.queue.rabbitmq.TbRabbitMqProducerTemplate;
import com.mortals.xhx.queue.rabbitmq.TbRabbitMqSettings;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
@ConditionalOnExpression("'${queue.type:null}'=='rabbitmq'")
public class RabbitMqTbCoreQueueFactory implements TbCoreQueueFactory {

    private final TbRabbitMqSettings rabbitMqSettings;
    private final TbQueueCoreSettings coreSettings;

    public RabbitMqTbCoreQueueFactory(TbRabbitMqSettings rabbitMqSettings, TbQueueCoreSettings coreSettings) {
        this.rabbitMqSettings = rabbitMqSettings;
        this.coreSettings = coreSettings;

    }

    @Override
    public TbQueueProducer<TbQueueMsg> createMsgProducer() {
        return new TbRabbitMqProducerTemplate<>(rabbitMqSettings, coreSettings.getTopic());

    }

    @Override
    public TbQueueConsumer<TbQueueMsg> createMsgConsumer() {

        return new TbRabbitMqConsumerTemplate<>(rabbitMqSettings, coreSettings.getTopic(), msg -> new TbQueueMsg() {
            @Override
            public String getKey() {
                return msg.getKey();
            }

            @Override
            public TbQueueMsgHeaders getHeaders() {
                return msg.getHeaders();
            }

            @Override
            public byte[] getData() {
                return msg.getData();
            }
        });
    }

    @Override
    public List<TbQueueConsumer<TbQueueMsg>> createListMsgConsumer(List<String> vhosts) {
        List<TbQueueConsumer<TbQueueMsg>> list =vhosts.stream().map(vhost->{
            rabbitMqSettings.setVHost(vhost);
            return new TbRabbitMqConsumerTemplate<TbQueueMsg>(rabbitMqSettings, coreSettings.getTopic(), msg -> new TbQueueMsg() {
                @Override
                public String getKey() {
                    return msg.getKey();
                }

                @Override
                public TbQueueMsgHeaders getHeaders() {
                    return msg.getHeaders();
                }

                @Override
                public byte[] getData() {
                    return msg.getData();
                }
            });

        }).collect(Collectors.toList());
        return list;
    }
}
