85 lines
2.8 KiB
Java
85 lines
2.8 KiB
Java
package pl.edu.amu.wmi.bookapi.service;
|
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.stereotype.Service;
|
|
import pl.edu.amu.wmi.bookapi.config.DateTimeProvider;
|
|
import pl.edu.amu.wmi.bookapi.models.MessageDocument;
|
|
import pl.edu.amu.wmi.bookapi.models.ThreadDocument;
|
|
import pl.edu.amu.wmi.bookapi.repositories.MessageRepository;
|
|
import pl.edu.amu.wmi.bookapi.repositories.ThreadRepository;
|
|
|
|
import java.util.Date;
|
|
import java.util.List;
|
|
import java.util.stream.Collectors;
|
|
|
|
@Service
|
|
public class MessageService {
|
|
|
|
DateTimeProvider dateTimeProvider;
|
|
ThreadRepository threadRepository;
|
|
MessageRepository messageRepository;
|
|
|
|
@Autowired
|
|
public MessageService(ThreadRepository threadRepository,
|
|
MessageRepository messageRepository,
|
|
DateTimeProvider dateTimeProvider) {
|
|
this.dateTimeProvider = dateTimeProvider;
|
|
this.threadRepository = threadRepository;
|
|
this.messageRepository = messageRepository;
|
|
}
|
|
|
|
public List<ThreadDocument> getThreads(String user) {
|
|
List<ThreadDocument> threads = threadRepository.findByParticipant(user);
|
|
return threads
|
|
.stream()
|
|
.map(it -> {
|
|
it.getParticipantsIds().remove(user);
|
|
return it;
|
|
})
|
|
.collect(Collectors.toList());
|
|
}
|
|
|
|
public List<MessageDocument> getMessagesInThread(String threadId, String userId) {
|
|
return messageRepository.findByUserAndThreadId(threadId, userId);
|
|
}
|
|
|
|
public void createMessage(String content, String author, String recipient) {
|
|
String threadId = null;
|
|
List<ThreadDocument> foundThreads = threadRepository.findByParticipants(author, recipient);
|
|
|
|
if(foundThreads.size() == 0) {threadId = createThread(author, recipient);} else {
|
|
threadId = foundThreads.get(0).getId();
|
|
}
|
|
|
|
createMessageInThread(
|
|
threadId,
|
|
author,
|
|
recipient,
|
|
content,
|
|
Date.from(dateTimeProvider.time())
|
|
);
|
|
}
|
|
|
|
private String createThread(String author, String recipient) {
|
|
ThreadDocument savedThread = threadRepository.save(new ThreadDocument(List.of(author, recipient)));
|
|
return savedThread.getId();
|
|
}
|
|
|
|
private void createMessageInThread(
|
|
String threadId,
|
|
String author,
|
|
String recipient,
|
|
String content,
|
|
Date date) {
|
|
messageRepository.save(
|
|
new MessageDocument(
|
|
author,
|
|
recipient,
|
|
date,
|
|
content,
|
|
threadId
|
|
)
|
|
);
|
|
}
|
|
}
|