package org.uned.agonzalo16.bitacora.web.comment;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.uned.agonzalo16.bitacora.dao.ArticleDao;
import org.uned.agonzalo16.bitacora.dao.CommentDao;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.Article;
import org.uned.agonzalo16.bitacora.domain.Comment;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;
@RequestMapping("/comment")
@Controller
@SessionAttributes({ "userAttribute" })
public class CommentController {
@Autowired
private ArticleDao articleDao;
@Autowired
private CommentDao commentDao;
@Autowired
private UserDao userDao;
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("article") CommentForm form, BindingResult result, @ModelAttribute("userAttribute") AuthenticatedUser user) {
if (result.hasErrors()) {
return "contributor/article/create";
}
Article article = articleDao.get(form.getArticleId());
Comment comment = new Comment();
comment.setContent(form.getContent());
comment.setCreationDate(new Date());
comment.setArticle(article);
comment.setUser(userDao.get(user.getId()));
if (form.getParentArticleId() != null) {
comment.setParentComment(commentDao.get(article, form.getParentArticleId()));
}
commentDao.merge(comment);
return "redirect:/article/" + form.getArticleId();
}
@RequestMapping(method = RequestMethod.POST, value = "/delete")
public String delete(@ModelAttribute("article") CommentDeleteForm form) {
Comment comment = commentDao.get(articleDao.get(form.getArticleId()), form.getCommentId());
comment.setDeleted(true);
comment.setDeleteReason(form.getReason());
commentDao.merge(comment);
return "redirect:/article/" + comment.getArticle().getId();
}
}