package com.forum.controller;

import com.forum.entity.Comment;
import com.forum.entity.User;
import com.forum.service.ForumService;
import com.forum.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private ForumService forumService;

//    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{forumId}")  //展示
    public String getComments(@PathVariable Long forumId, Model model){
        model.addAttribute("comments", commentService.getCommentByForumId(forumId));
        model.addAttribute("forum", forumService.getDetailedForum(forumId));
        return "forum :: commentList";
    }

    @PostMapping("/comments")   //提交
    public String postComment(Comment comment, HttpSession session){
        Long forumId = comment.getForum().getId();
        comment.setForum(forumService.getDetailedForum(forumId));  //绑定评论
        comment.setForumId(forumId);
        User user = (User) session.getAttribute("user");
        if (user != null){   //用户存在
            comment.setAvatar(user.getAvatar());
            comment.setUserComment(true);
        }else {
            comment.setAvatar(avatar);
        }
        System.out.println(comment);
         String contents = comment.getContent();
         String arr[]={"垃圾","滚","混蛋","王八蛋","有病","美白","祛痘","祛斑","纯天然","换肤","去除皱纹","防脱发","生发","无毒","安全","瘦脸","助眠",};
        for (int i = 0; i < arr.length; i++) {
            contents= contents.replaceAll(arr[i],"*");
            System.out.println(contents);
            comment.setContent(contents);

        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + forumId;
    }
}
