package cn.ftebox.controller;


import cn.ftebox.entity.Blog;
import cn.ftebox.entity.Blogger;
import cn.ftebox.entity.Comment;
import cn.ftebox.service.BlogService;
import cn.ftebox.service.CommentService;
import cn.ftebox.util.Const;
import cn.ftebox.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 提交评论
 */
@Controller
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private CommentService commentService;
    @Resource
    private BlogService blogService;

    @RequestMapping("/save.do")
    public String save(Comment comment, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        Blogger blogger = (Blogger) SecurityUtils.getSubject().getSession().getAttribute(Const.CURRENT_USER);
        comment.setUserIp(blogger==null?"匿名": blogger.getUserName());
        int resultTotal = 0;
        JSONObject result = new JSONObject();
        if (comment.getId() == null) {
            resultTotal = commentService.add(comment);
            Blog blog = blogService.findById(comment.getBlog().getId());
            blog.setReplyHit(blog.getReplyHit() + 1);
            blogService.update(blog);
        }
        ResponseUtil.write(response,resultTotal > 0?result.put("success",Boolean.TRUE):result.put("error",Boolean.FALSE));
        return null;
    }


}
