-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Answer.java
72 lines (62 loc) · 2.13 KB
/
Answer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package stackoverflow;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Answer implements Votable, Commentable {
private final int id;
private final String content;
private final User author;
private final Question question;
private boolean isAccepted;
private final Date creationDate;
private final List<Comment> comments;
private final List<Vote> votes;
public Answer(User author, Question question, String content) {
this.id = generateId();
this.author = author;
this.question = question;
this.content = content;
this.creationDate = new Date();
this.votes = new ArrayList<>();
this.comments = new ArrayList<>();
this.isAccepted = false;
}
@Override
public void vote(User user, int value) {
if (value != 1 && value != -1) {
throw new IllegalArgumentException("Vote value must be either 1 or -1");
}
votes.removeIf(v -> v.getUser().equals(user));
votes.add(new Vote(user, value));
author.updateReputation(value * 10); // +10 for upvote, -10 for downvote
}
@Override
public int getVoteCount() {
return votes.stream().mapToInt(Vote::getValue).sum();
}
@Override
public void addComment(Comment comment) {
comments.add(comment);
}
@Override
public List<Comment> getComments() {
return new ArrayList<>(comments);
}
public void markAsAccepted() {
if (isAccepted) {
throw new IllegalStateException("This answer is already accepted");
}
isAccepted = true;
author.updateReputation(15); // +15 reputation for accepted answer
}
private int generateId() {
return (int) (System.currentTimeMillis() % Integer.MAX_VALUE);
}
// Getters
public int getId() { return id; }
public User getAuthor() { return author; }
public Question getQuestion() { return question; }
public String getContent() { return content; }
public Date getCreationDate() { return creationDate; }
public boolean isAccepted() { return isAccepted; }
}