package com.tzld.piaoquan.recommend.server.framework.recaller.provider;

import com.google.common.base.Function;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.tzld.piaoquan.recommend.server.framework.candidiate.Entry;
import com.tzld.piaoquan.recommend.server.framework.candidiate.Queue;
import com.tzld.piaoquan.recommend.server.framework.candidiate.QueueName;
import com.tzld.piaoquan.recommend.server.framework.utils.RedisSmartClient;
import com.tzld.piaoquan.recommend.server.model.Video;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;


public class RedisBackedQueueWithoutMetaCacheLoader extends CacheLoader<QueueName, Pair<Long, Queue<Video>>> {

    private static final Logger logger = LoggerFactory.getLogger(RedisBackedQueueWithoutMetaCacheLoader.class);
    private final RedisSmartClient client;

    public RedisBackedQueueWithoutMetaCacheLoader(RedisSmartClient client) {
        this.client = client;
    }

    @Override
    public Pair<Long, Queue<Video>> load(QueueName name) throws Exception {
        String valueJson = client.get(name.toString());
        Index index = new Index(name.toString(), valueJson);

        if (null == index || CollectionUtils.isEmpty(index.getIndexEntryList())) {
//            logger.error("empty_index_fetch");
        }

        //IndexEntry 转化到Entry中 video 格式
        Queue<Video> queue = new Queue<Video>(name.toString());
        Iterable<Entry<Video>> iterable = Iterables.transform(index.getIndexEntryList(), new Function<IndexEntry, Entry<Video>>() {
            @Nullable
            @Override
            public Entry<Video> apply(IndexEntry indexEntry) {
                Video recallData = new Video();
                recallData.setVideoId(Long.valueOf(indexEntry.getItemId()));
                recallData.setPushFrom(name.toString());
                Entry<Video> entry = new Entry<Video>(recallData, indexEntry.getItemId());
                entry.addScore("ordering", indexEntry.getScore());
                return entry;
            }
        });
        queue.addAll(Lists.newArrayList(iterable));

        return Pair.of(Long.MIN_VALUE, queue);
    }
}
