package com.yida.data.websocket.config;

import com.rabbitmq.client.Channel;
import com.yida.data.msg.dto.WebsocketMsgDTO;
import com.yida.data.rabbit.constant.RabbitConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
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.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class RabbitReceiver {

    private final SimpMessagingTemplate simpMessagingTemplate;

    @RabbitListener(bindings = @QueueBinding(
        value = @Queue(RabbitConstant.MSG_WEBSOCKET_QUEUE),
        exchange = @Exchange(RabbitConstant.MSG_EXCHANGE)
    ))
    public void receivePosition(WebsocketMsgDTO msg, Channel channel, Message message) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            simpMessagingTemplate.convertAndSendToUser(msg.getUserId().toString(), "/msg", msg.getContent());
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("推送websocket失败", e);
        }
    }
}
