package com.tzld.piaoquan.recommend.server.service.rank.extractor;
import com.tzld.piaoquan.recommend.server.model.Video;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

public class RankExtractorItemTags {
    public RedisTemplate<String, String> redisTemplate;
    public RankExtractorItemTags(RedisTemplate<String, String> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    public void processor(List<Video> rovVideos, List<Video> flowVideos, List<Video> douHotFlowPoolVideos) {
        List<Long> videoIds = new ArrayList<>();
        for (Video v : rovVideos) {
            videoIds.add(v.getVideoId());
        }
        for (Video v : flowVideos) {
            videoIds.add(v.getVideoId());
        }
        for (Video v : douHotFlowPoolVideos) {
            videoIds.add(v.getVideoId());
        }

        Map<Long, List<String>> videoTagDict = getVideoTags(redisTemplate, videoIds);
        for (Video v : rovVideos) {
            v.setTags(videoTagDict.getOrDefault(v.getVideoId(), new ArrayList<>()));
        }
        for (Video v : flowVideos) {
            v.setTags(videoTagDict.getOrDefault(v.getVideoId(), new ArrayList<>()));
        }
        for (Video v : douHotFlowPoolVideos) {
            v.setTags(videoTagDict.getOrDefault(v.getVideoId(), new ArrayList<>()));
        }
    }

    public static Map<Long, List<String>> getVideoTags(RedisTemplate<String, String> redisHelper, List<Long> videoIds) {
        String REDIS_PREFIX = "alg_recsys_video_tags_";
        List<String> redisKeys = new ArrayList<>();
        for (Long videoId : videoIds) {
            redisKeys.add(REDIS_PREFIX + String.valueOf(videoId));
        }
        List<String> videoTags = redisHelper.opsForValue().multiGet(redisKeys);
        Map<Long, List<String>> videoTagDict = new HashMap<>();
        if (videoTags != null) {
            for (int i = 0; i < videoTags.size(); i++) {
                String tagsStr = videoTags.get(i);
                List<String> tags = new ArrayList<>();
                if (tagsStr != null && !tagsStr.isEmpty()) {
                    String[] tagsArray = tagsStr.split(",");
                    tags = new ArrayList<>(Arrays.asList(tagsArray));
                }
                videoTagDict.put(videoIds.get(i), tags);
            }
        }
        return videoTagDict;
    }
}
