package org.ros.chatto.websocket;

import java.security.Principal;

import javax.validation.Valid;

import org.ros.chatto.dto.ChatMessageDTO;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import lombok.RequiredArgsConstructor;

@Controller
@RequiredArgsConstructor
public class WebSocketController {

    private final SimpMessagingTemplate smt;

    @MessageMapping("/ping")
    public void send2(Principal principal) throws Exception {
        smt.convertAndSendToUser(principal.getName(), "/queue/ping", "pong");
    }

    @MessageMapping("/chat")
    public void send(@Valid @Payload final ChatMessageDTO message)
            throws Exception {
        smt.convertAndSendToUser(message.getFromUser(), "/queue/reply",
                message);
        smt.convertAndSendToUser(message.getToUser(), "/queue/reply", message);
    }

    @GetMapping("/ws")
    public String wsPage() {
        return "ws";
    }
}