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

import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.data.db.mapper.ImagePostMapper;
import cn.reghao.tnb.content.app.data.model.vo.ImageAlbumQuery;
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 ImagePostMapper imagePostMapper;
    private final PostAlbumMapper postAlbumMapper;
    private final ContentPermission contentPermission;

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

    public UserContentData getUserContentData(long userId) {
        long owner = UserContext.getUser();
        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);

        ImageAlbumQuery imageAlbumQuery;
        if (owner == userId) {
            imageAlbumQuery = new ImageAlbumQuery.Builder()
                    .userId(userId)
                    .build();
        } else {
            List<Integer> scopes = contentPermission.getUserScopes();
            imageAlbumQuery = new ImageAlbumQuery.Builder()
                    .userId(userId)
                    .scope(scopes)
                    .build();
        }
        int imageCount = imagePostMapper.countByCriteria(imageAlbumQuery);

        AlbumQuery albumQuery;
        if (owner == userId) {
            albumQuery = new AlbumQuery.Builder().createBy(userId).build();
        } else {
            List<Integer> scopes = contentPermission.getUserScopes();
            albumQuery = new AlbumQuery.Builder().createBy(userId).scope(scopes).build();
        }

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