package cn.reghao.tnb.content.app.vod.service;

import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.api.constant.PostType;
import cn.reghao.tnb.content.app.vod.db.mapper.PostAlbumMapper;
import cn.reghao.tnb.content.app.vod.db.mapper.VideoPostMapper;
import cn.reghao.tnb.content.app.vod.model.query.AlbumQuery;
import cn.reghao.tnb.content.app.vod.model.vo.UserContentData;
import cn.reghao.tnb.content.app.vod.model.query.VideoQuery;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author reghao
 * @date 2022-08-05 13:49:28
 */
@Service
public class ContentService {
    private final VideoPostMapper videoPostMapper;
    private final PostAlbumMapper postAlbumMapper;
    private final ContentPermission contentPermission;

    public ContentService(VideoPostMapper videoPostMapper, PostAlbumMapper postAlbumMapper,
                          ContentPermission contentPermission) {
        this.videoPostMapper = videoPostMapper;
        this.postAlbumMapper = postAlbumMapper;
        this.contentPermission = contentPermission;
    }

    public UserContentData getUserContentData(long userId) {
        long owner = UserContext.getUserId();
        VideoQuery videoQuery;
        if (owner == userId) {
            videoQuery = new VideoQuery.Builder().userId(userId).build();
        } else {
            List<Integer> scopes = contentPermission.getUserScopes();
            videoQuery = new VideoQuery.Builder().scope(scopes).userId(userId).build();
        }
        int videoCount = videoPostMapper.countByCriteria(videoQuery);

        AlbumQuery.Builder builder = new AlbumQuery.Builder()
                .postType(PostType.Image.getCode())
                .createBy(userId);
        if (owner != userId) {
            List<Integer> scopes = contentPermission.getUserScopes();
            builder.scope(scopes);
        }
        int imageCount = postAlbumMapper.countByCriteria(builder.build());

        AlbumQuery.Builder builder1 = new AlbumQuery.Builder()
                .postType(PostType.Video.getCode())
                .createBy(userId);
        if (owner != userId) {
            List<Integer> scopes = contentPermission.getUserScopes();
            builder1.scope(scopes);
        }

        int albumCount = postAlbumMapper.countByCriteria(builder1.build());
        return new UserContentData(videoCount, imageCount, albumCount);
    }
}
