package com.tzld.piaoquan.recommend.server.implement.recall;

import com.tzld.piaoquan.recommend.server.framework.candidiate.Candidate;
import com.tzld.piaoquan.recommend.server.framework.common.User;
import com.tzld.piaoquan.recommend.server.framework.recaller.AbstractFilter;
import com.tzld.piaoquan.recommend.server.framework.recaller.FilterConfigInfo;
import com.tzld.piaoquan.recommend.server.gen.recommend.RecommendRequest;
import com.tzld.piaoquan.recommend.server.model.RecommendParam;
import com.tzld.piaoquan.recommend.server.model.Video;
import com.tzld.piaoquan.recommend.server.service.RecommendService;
import com.tzld.piaoquan.recommend.server.service.ServiceBeanFactory;
import com.tzld.piaoquan.recommend.server.service.filter.FilterParam;
import com.tzld.piaoquan.recommend.server.service.filter.FilterResult;
import com.tzld.piaoquan.recommend.server.service.filter.RegionFilterService;
import com.tzld.piaoquan.recommend.server.service.recall.FilterParamFactory;
import com.tzld.piaoquan.recommend.server.service.recall.RecallParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * TODO 有性能问题，暂时废弃
 *
 * @author sunxy
 */
public class HistoryLongPeriodFilter extends AbstractFilter<Video> {

    private static final Logger LOGGER = LoggerFactory.getLogger(HistoryLongPeriodFilter.class);

    private final RegionFilterService filterService;
    private final RecommendService recommendService;

    public HistoryLongPeriodFilter(FilterConfigInfo filterConfigInfo, RecommendRequest requestContext, User user) {
        super(filterConfigInfo, requestContext, user);
        filterService = ServiceBeanFactory.getBean(RegionFilterService.class);
        recommendService = ServiceBeanFactory.getBean(RecommendService.class);
    }

    @Override
    public void doFilter(Candidate candidate, List<Video> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        RecommendParam recommendParam = recommendService.genRecommendParam(requestContext, 1);
        RecallParam recallParam = recommendService.convertToRecallParam(recommendParam);
        FilterParam filterParam = FilterParamFactory.create(recallParam,
                list.stream().map(Video::getVideoId).collect(Collectors.toList()));
        FilterResult filterResult = filterService.filter(filterParam);
        if (filterResult != null && filterResult.getVideoIds() != null) {
            list.removeIf(video -> !filterResult.getVideoIds().contains(video.getVideoId()));
        }
    }

}
