@Override
@SuppressWarnings("unchecked")
public Document addCommentToAlert(CommentAddRemoveRequest request, Document latest) throws IOException {
if (latest == null || latest.getDocument() == null) {
throw new IOException(String.format("Unable to add comment. Document with guid %s cannot be found.",
request.getGuid()));
}
List<Map<String, Object>> comments = (List<Map<String, Object>>) latest.getDocument()
.getOrDefault(COMMENTS_FIELD, new ArrayList<>());
List<Map<String, Object>> originalComments = new ArrayList<>(comments);
List<Map<String, Object>> commentsMap = new ArrayList<>();
for (Map<String, Object> comment : originalComments) {
commentsMap.add(new AlertComment(comment).asMap());
}
commentsMap.add(new AlertComment(
request.getComment(),
request.getUsername(),
request.getTimestamp())
.asMap());
Document newVersion = new Document(latest);
newVersion.getDocument().put(COMMENTS_FIELD, commentsMap);
return update(newVersion, Optional.empty());
}