package com.sharomank.domain.base;
import com.sharomank.domain.Account;
import com.sharomank.domain.Vote;
import org.apache.commons.collections.CollectionUtils;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author sharomank
* @since 25/01/13 00:40
*/
@MappedSuperclass
public abstract class BaseItemEntity extends BaseTextEntity {
@ManyToOne(optional = false)
private Account account;
@Column
private Long rating = 0L;
@OneToMany(cascade = CascadeType.ALL)
private List<Vote> votes;
public void addVote(Account voteAccount, boolean plus) {
if (account.getId().equals(voteAccount.getId())) {
return;
}
if (CollectionUtils.isEmpty(getVotes())) {
setVotes(new ArrayList<Vote>());
}
for (Vote v : getVotes()) {
if (v.getAccount().getId().equals(voteAccount.getId())) {
return;
}
}
Vote v = new Vote();
v.setAccount(voteAccount);
v.setPlus(plus);
votes.add(v);
calculateRating();
}
private void calculateRating() {
Long newRating = 0L;
for (Vote v : getVotes()) {
newRating += (v.isPlus() ? 1 : -1);
}
setRating(newRating);
}
@Override
public String toString() {
return "rating=" + rating + ", text=" + getText();
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Long getRating() {
return rating;
}
public void setRating(Long rating) {
this.rating = rating;
}
public List<Vote> getVotes() {
return votes;
}
public void setVotes(List<Vote> votes) {
this.votes = votes;
}
}