package me.qwq.doghouse.cache;

import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import me.qwq.doghouse.annotation.UpdatePosts;
import me.qwq.doghouse.entity.Post;
import me.qwq.doghouse.pojo.dto.PageQuery;
import me.qwq.doghouse.service.CommentService;
import me.qwq.doghouse.service.post.PostService;

/**
 * 对需要更新 PostViews/CommentsCount 的返回值进行修改注入<br>
 * 适用于：频繁更新某个特定值（此处为 PostViews 和 CommentsCount）后更新 Post
 * @author Doghole
 *
 */
@Aspect
@Component
public class PostViewsAndCommentsCountAspect {

    @Autowired
    PostService postService;
    
    @Autowired
    CommentService commentService;
    
    @Around("@annotation(annotation)")
    public Object around(ProceedingJoinPoint joinPoint, UpdatePosts annotation) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object result = joinPoint.proceed(args);
        if (result == null) return result;
        if (!annotation.commentsCount() && !annotation.postViews()) return result;
        if (result.getClass() == PageQuery.class) {
            PageQuery<?> pageQuery = (PageQuery<?>)result;
            pageQuery.getRecords().forEach(post -> updatePost(post, annotation));
            return result;
        }
        else if (result instanceof List) {
            List<?> list = (List<?>)result;
            if (list.isEmpty() || list.get(0).getClass() != Post.class) return result;
            list.forEach(post -> updatePost(post, annotation));
            return result;
        }
        return result;
    }
    
    private void updatePost(Object post, UpdatePosts annotation) {
        if (annotation.commentsCount()) {
            Long postCommentCount = commentService.getPostCommentCount(((Post)post).getPostId());
            ((Post)post).setCommentCount(postCommentCount);
        }
        if (annotation.postViews()) {
            Long postViews = postService.getPostViews(
                    ((Post)post).getPostId());
            ((Post)post).setPostViews(postViews);
        }
    }

}
