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

import com.yiring.websocket.config.WebSocketStompConfig;
import lombok.NonNull;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

/**
 * @author Jim
 */
@Component
public class AbstractMessageHandler {

    public SimpMessageHeaderAccessor getAccessor(@NonNull Message<?> message) {
        Class<? extends SimpMessageHeaderAccessor> clazz = WebSocketStompConfig.stompMode
            ? StompHeaderAccessor.class
            : SimpMessageHeaderAccessor.class;
        return MessageHeaderAccessor.getAccessor(message, clazz);
    }

    public boolean isConnect(@NonNull SimpMessageHeaderAccessor accessor) {
        if (accessor instanceof StompHeaderAccessor) {
            return StompCommand.CONNECT.equals(((StompHeaderAccessor) accessor).getCommand());
        } else {
            return SimpMessageType.CONNECT.equals(accessor.getMessageType());
        }
    }

    public boolean isDisconnect(@NonNull SimpMessageHeaderAccessor accessor) {
        if (accessor instanceof StompHeaderAccessor) {
            return StompCommand.DISCONNECT.equals(((StompHeaderAccessor) accessor).getCommand());
        } else {
            return SimpMessageType.DISCONNECT.equals(accessor.getMessageType());
        }
    }

    public Boolean isConnected(@NonNull SimpMessageHeaderAccessor accessor) {
        if (accessor instanceof StompHeaderAccessor) {
            return StompCommand.CONNECTED.equals(((StompHeaderAccessor) accessor).getCommand());
        } else {
            return SimpMessageType.CONNECT_ACK.equals(accessor.getMessageType());
        }
    }
}
