package ua.kpi.controller;

import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import ua.kpi.dto.request.SendMessageRequest;
import ua.kpi.dto.response.MessageItem;
import ua.kpi.entity.Message;
import ua.kpi.repository.MessageRepository;
import ua.kpi.repository.UserRepository;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @author Mykola Yashchenko
 */
@Controller
@AllArgsConstructor
public class MessageController {

    private final MessageRepository messageRepository;
    private final UserRepository userRepository;
    private final MapperFacade mapperFacade;

    @MessageMapping("/messages")
    @SendTo("/topic/messages")
    public List<MessageItem> getMessages() {
        return Collections.emptyList();
    }

    @MessageMapping("/messages/send")
    @SendTo("/topic/messages")
    public List<MessageItem> sendMessage(@Payload SendMessageRequest sendMessageRequest, Principal principal) {
        Message message = mapperFacade.map(sendMessageRequest, Message.class);
        message.setTime(LocalDateTime.now());
        message.setDoctor(userRepository.findByEmail(principal.getName()));

        messageRepository.save(message);

        MessageItem messageItem = new MessageItem();
        messageItem.setText(message.getText());
        messageItem.setTime(message.getTime().toString());
        messageItem.setDoctorName(principal.getName());

        return Collections.singletonList(messageItem);
    }
}

@@ -663,16 +663,52 @@
 il.List;
+%0Aimport java.util.stream.Collectors;
 %0A%0A/**%0A *
@@ -1082,31 +1082,132 @@
 urn 
-Collections.empty
+messageRepository.findAll().stream()%0A                .map(this::toMessageItem)%0A                .collect(Collectors.to
 List()
+)
 ;%0A  
@@ -1632,24 +1632,154 @@
 (message);%0A%0A
+        return Collections.singletonList(toMessageItem(message));%0A    %7D%0A%0A    private MessageItem toMessageItem(Message message) %7B%0A
         Mess
@@ -1964,31 +1964,41 @@
 ame(
-principal.getName
+message.getDoctor().getEmail
 ());%0A
-%0A
     
@@ -2012,34 +2012,8 @@
 urn 
-Collections.singletonList(
 mess
@@ -2019,17 +2019,16 @@
 sageItem
-)
 ;%0A    %7D%0A

return all messages for request