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

import cn.reghao.tnb.content.api.constant.PostScope;
import cn.reghao.tnb.content.api.constant.RcmdMode;
import cn.reghao.tnb.content.api.dto.VideoCard;
import cn.reghao.tnb.content.app.util.redis.ds.RedisList;
import cn.reghao.tnb.content.app.util.redis.ds.RedisSet;
import cn.reghao.tnb.content.app.vod.service.ContentPermission;
import cn.reghao.tnb.content.app.vod.service.VideoPostQuery;
import cn.reghao.tnb.content.app.vod.service.rcmd.RedisKeys;
import cn.reghao.tnb.content.app.vod.service.rcmd.UserInterestBased;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2024-04-22 17:22:35
 */
@Slf4j
public class RcmdTask implements Runnable {
    private final RcmdData rcmdData;
    private final RedisSet redisSet;
    private final RedisList redisList;
    private final VideoPostQuery videoPostQuery;
    private final ContentPermission contentPermission;
    private final int mode;
    private UserInterestBased userInterestBased;

    public RcmdTask(RcmdData rcmdData, VideoPostQuery videoPostQuery, RedisSet redisSet, RedisList redisList,
                    ContentPermission contentPermission, int mode) {
        this.rcmdData = rcmdData;
        this.videoPostQuery = videoPostQuery;
        this.redisSet = redisSet;
        this.redisList = redisList;
        this.contentPermission = contentPermission;
        this.mode = mode;
    }

    public void run() {
        long loginUser = rcmdData.getUserId();
        String dislikeKey = RedisKeys.getUserDislikeKey(loginUser);
        List<String> dislikeVideos = redisList.getAll(dislikeKey).stream()
                .map(object -> (String) object)
                .collect(Collectors.toList());

        int size = rcmdData.getSize();
        List<Integer> userScopes = contentPermission.getUserScopes(loginUser);
        long start = System.currentTimeMillis();
        try {
            if (mode == RcmdMode.VIP.getValue()) {
                userScopes.clear();
                userScopes.add(PostScope.PROTECT.getCode());
            }

            List<String> videoIds = videoPostQuery.getRandomVideoIds(userScopes, size);
            if (!videoIds.isEmpty()) {
                List<VideoCard> videoCards = videoPostQuery.getVideoCards(videoIds);
                String itemsKey = RedisKeys.getUserItemKey(loginUser);
                VideoCard[] arr = videoCards.toArray(new VideoCard[0]);
                redisSet.sadd(itemsKey, arr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String requestId = MDC.get("request_id");
        log.info("{}: {}'s rcmd-task cost {}s", requestId, loginUser, (System.currentTimeMillis()-start)/1000);
    }
}
