package org.springblade.websocket.controller;

import org.springblade.core.tool.api.R;
import org.springblade.websocket.constant.WebsocketConstant;
import org.springblade.websocket.model.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
//import org.springframework.messaging.simp.SimpMessageSendingOperations;

/**
 * ChatController
 *
 * @author rajeevkumarsingh
 */
//@Controller
//@AllArgsConstructor
public class ChatController {

//	private SimpMessageSendingOperations messagingTemplate;

	@Autowired
	private SimpMessagingTemplate messagingTemplate;

	@MessageMapping("/chat.sendMessage")
	@SendTo("/topic/public")
	public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
		return chatMessage;
	}

	@MessageMapping("/chat.addUser")
	@SendTo("/topic/public")
	public ChatMessage addUser(@Payload ChatMessage chatMessage,
							   SimpMessageHeaderAccessor headerAccessor) {
		// Add username in web socket session
		headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
		return chatMessage;
	}

	/**
	 * 功能: 测试消息推送
	 * 作者: DSH
	 * 创建日期: 2022/3/26
	 * @param
	 * @return: org.springblade.core.tool.api.R<java.lang.Object>
	 */
	@GetMapping("/ws/send")
	public R<Object> getConfig() {
		messagingTemplate.convertAndSend(WebsocketConstant.DESTINATION_PUBLIC, "公共消息" + LocalDateTime.now().getSecond());
		messagingTemplate.convertAndSend(WebsocketConstant.DESTINATION_EVENT, "大事记" + LocalDateTime.now().getSecond());
		return R.data(null);
	}

}
