/* (C) 2022 YiRing, Inc. */
package com.yiring.websocket.interceptor;

import com.alibaba.fastjson2.JSON;
import com.yiring.websocket.domain.StompPrincipal;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * ClientOutboundChannelInterceptor
 * 向客户端输出消息的拦截器
 *
 * @author ifzm
 * @version 0.1
 * 2019/10/12 11:05
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class ClientOutboundChannelInterceptor implements ChannelInterceptor {

    final AbstractMessageHandler handler;

    @Override
    public Message<?> preSend(@NonNull Message<?> message, @NonNull MessageChannel channel) {
        SimpMessageHeaderAccessor accessor = handler.getAccessor(message);
        Assert.state(accessor != null, "No accessor");

        if (handler.isConnected(accessor)) {
            StompPrincipal principal = (StompPrincipal) accessor.getUser();
            return MessageBuilder.createMessage(JSON.toJSONBytes(principal), message.getHeaders());
        }

        return message;
    }
}
