22301102 | 43e9dfe | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 1 | package com.pt.service; |
| 2 | |
| 3 | import com.pt.entity.Comment; |
| 4 | import com.pt.repository.CommentRepository; |
| 5 | import org.springframework.beans.factory.annotation.Autowired; |
| 6 | import org.springframework.stereotype.Service; |
| 7 | |
| 8 | import java.util.List; |
| 9 | |
| 10 | @Service |
| 11 | public class CommentService { |
| 12 | |
| 13 | @Autowired |
| 14 | private CommentRepository commentRepository; |
| 15 | |
| 16 | public CommentService(CommentRepository commentRepository) { |
| 17 | this.commentRepository = commentRepository; |
| 18 | } |
| 19 | |
22301102 | f567030 | 2025-06-08 14:10:02 +0800 | [diff] [blame^] | 20 | public void addComment(String content, String username, int postId, Integer reviewer) { |
| 21 | System.out.println("Adding comment: " + content + " by " + username + " on post ID: " + postId + " with reviewer ID: " + reviewer); |
22301102 | 43e9dfe | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 22 | Comment comment = new Comment(); |
| 23 | comment.setContent(content); |
| 24 | comment.setWriter(username); |
| 25 | comment.setParentPost(postId); |
22301102 | f567030 | 2025-06-08 14:10:02 +0800 | [diff] [blame^] | 26 | if(reviewer != null) { |
| 27 | System.out.println("Setting reviewer ID: " + reviewer); |
| 28 | comment.setReviewer(reviewer); |
| 29 | } |
22301102 | 43e9dfe | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 30 | commentRepository.save(comment); |
| 31 | } |
| 32 | |
| 33 | public void deleteComment(int commentId) { |
| 34 | commentRepository.deleteById(commentId); |
| 35 | } |
| 36 | |
| 37 | public List<Comment> getCommentsByPostId(int postId) { |
| 38 | List<Comment> comments = commentRepository.findByParentPost(postId); |
| 39 | comments.sort( |
| 40 | // Sort comments by publish date in descending order |
| 41 | (c1, c2) -> c2.getPublishDate().compareTo(c1.getPublishDate()) |
| 42 | ); |
| 43 | return comments; |
| 44 | } |
22301102 | f567030 | 2025-06-08 14:10:02 +0800 | [diff] [blame^] | 45 | |
| 46 | public Comment getCommentById(int commentId) { |
| 47 | return commentRepository.findById(commentId).orElse(null); |
| 48 | } |
22301102 | 43e9dfe | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 49 | } |