
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.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;

@Slf4j
public class TbRabbitMqConsumerTemplate<T extends TbQueueMsg> extends AbstractTbQueueConsumerTemplate<GetResponse, T> {

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

    private final Gson gson = new Gson();

    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);
                        return null;
                        //  throw new RuntimeException("Failed to get messages from queue." , e);
                    }
                }).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());
        //queues.forEach(admin::createTopicIfNotExists);
    }

    @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.");
            }
        }
    }

    public T decode(GetResponse message) {

        // log.info("getRespBody:" + new String(message.getBody()));
        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");
            System.out.println("receivedPayLoadStr:" + payloadStr);

            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);

//            String clientIdStr = ((JSONObject) ((JSONObject) map.get("headers")).get("data")).getString("clientId");
//            String qosStr = ((JSONObject) ((JSONObject) map.get("headers")).get("data")).getString("qos");
//            String timestampStr = ((JSONObject) ((JSONObject) map.get("headers")).get("data")).getString("timestamp");
//            if(!ObjectUtils.isEmpty(clientIdStr)){
//                headers.put(MessageHeader.CLIENTID, clientIdStr);
//            }
//            if(!ObjectUtils.isEmpty(qosStr)){
//                headers.put(MessageHeader.TOPIC,qosStr);
//            }
//            if(!ObjectUtils.isEmpty(timestampStr)) {
//                headers.put(MessageHeader.TIMESTAMP, timestampStr);
//            }
            msg.setHeaders(headers);
            // log.info("msg:" + msg.toString());
            return decoder.decode(msg);
        } catch (Exception e) {
            log.error("反序列化异常！", e);
            return null;
        }

    }
}
