
package com.mortals.xhx.queue.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.queue.*;
import com.mortals.xhx.queue.kafka.AbstractTbQueueConsumerTemplate;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.GetResponse;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
/**
 * 消费连接池
 *
 * @author: zxfei
 * @date: 2022/4/25 13:49
 */
@Slf4j
public class TbRabbitMqConsumerTemplate<T extends TbQueueMsg> extends AbstractTbQueueConsumerTemplate<GetResponse, T> {

    private final TbQueueMsgDecoder<T> decoder;
    @Getter
    private Channel channel;
    private Connection connection;

    private volatile Set<String> queues;

    public TbRabbitMqConsumerTemplate(TbRabbitMqSettings rabbitMqSettings, String topic, TbQueueMsgDecoder<T> decoder) {
        super(topic);
        this.decoder = decoder;
        try {
            connection = rabbitMqSettings.getConnectionFactory().newConnection();
            channel = connection.createChannel();
            log.info("channelNumber:" + channel.getChannelNumber());
        } catch (IOException | TimeoutException e) {
            log.error("Failed to create connection.", e);
        }
        stopped = false;
    }

    @Override
    protected List<GetResponse> doPoll(long durationInMillis) {
        List<GetResponse> result = queues.stream()
                .map(queue -> {
                    try {
                        GetResponse getResponse = channel.basicGet(queue, true);
                        return getResponse;
                    } catch (IOException e) {
                        log.error("Failed to get messages from queue: {},{}" , queue,e);
                        return null;
                    }
                }).filter(Objects::nonNull).collect(Collectors.toList());
        if (result.size() > 0) {
            return result;
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    protected void doSubscribe(List<String> topicNames) {
        queues = partitions.stream()
                .map(TopicPartitionInfo::getFullTopicName)
                .collect(Collectors.toSet());
    }

    @Override
    protected void doCommit() {
        try {
            channel.basicAck(0, true);
        } catch (IOException e) {
            log.error("Failed to ack messages.", e);
        }
    }

    @Override
    protected void doUnsubscribe() {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                log.error("Failed to close the channel.");
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                log.error("Failed to close the connection.");
            }
        }
    }

    @Override
    public String getChannelNumber() {
        return channel.getChannelNumber()+"";
    }

    public T decode(GetResponse message) {
        try {
            DefaultTbQueueMsg msg = new DefaultTbQueueMsg();
            // DefaultTbQueueMsg msg = gson.fromJson(new String(message.getBody()), DefaultTbQueueMsg.class);
            Map<String, Object> map = JSON.parseObject(new String(message.getBody()), HashMap.class);
            msg.setKey((String)map.get("key"));
            String payloadStr = (String)map.get("data");
            byte[] payloadDecodeByte = Base64.getDecoder().decode(payloadStr);

            msg.setData(payloadDecodeByte);
            TbQueueMsgHeaders headers = new DefaultTbQueueMsgHeaders();
            String headerStr = ((JSONObject) map.get("headers")).getString("data");
            HashMap<String, String> hashMap = JSON.parseObject(headerStr, HashMap.class);
            headers.setData(hashMap);
            msg.setHeaders(headers);
            log.debug("msg:" + msg.toString());
            return decoder.decode(msg);
        } catch (Exception e) {
            log.error("反序列化异常！", e);
            return null;
        }

    }
}
