package com.tzld.piaoquan.recommend.server.service.flowpool;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.reflect.TypeToken;
import com.tzld.piaoquan.recommend.server.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author dyp
 */
@Service
@Slf4j
public class FlowPoolConfigService {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, String> redisTemplate;
    @Value("${flow.pool.upgrade.switch:true}")
    private boolean flowPoolUpgradeSwitch;

    private LoadingCache<String, Map<String, Double>> levelWeightConfigCache = CacheBuilder.newBuilder()
            .maximumSize(10)
            .refreshAfterWrite(60, TimeUnit.SECONDS)
            .expireAfterWrite(60, TimeUnit.SECONDS)
            .expireAfterAccess(60, TimeUnit.SECONDS)
            .build(new CacheLoader<String, Map<String, Double>>() {
                @Override
                public Map<String, Double> load(String key) throws Exception {
                    String value = redisTemplate.opsForValue().get(key);
                    if (StringUtils.isEmpty(value)) {
                        value = "{\"1\": 1, \"2\": 1, \"3\": 1, \"4\": 1}";
                    }
                    return JSONUtils.fromJson(value, new TypeToken<Map<String, Double>>() {
                    }, Collections.emptyMap());
                }
            });


    public Map<String, Double> getLevelWeight4FlowPoolWithLevel() {
        try {
            return flowPoolUpgradeSwitch
                    ? levelWeightConfigCache.get("flow:pool:level:weight:v2")
                    : levelWeightConfigCache.get("flow:pool:level:recommend:weight");
        } catch (ExecutionException e) {
            log.error("getFlowPoolConfig error", e);
            return Collections.emptyMap();
        }
    }

    public Map<String, Double> getDouHotFLowPoolWithLevel() {
        try {
            return levelWeightConfigCache.get("dou:hot:flow:pool:level:weight");
        } catch (Exception e) {
            log.error("getDouHotFLowConfig error. \n", e);
            return Collections.emptyMap();
        }
    }
}
