package com.games.gateway.utils;

import com.alibaba.fastjson.JSON;
import com.games.gateway.config.GatewayBizConfig;
import com.games.gateway.domain.ServiceAuthRegist;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AuthCache implements InitializingBean {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private LoadingCache<String, ServiceAuthRegist> authCache;

    public ServiceAuthRegist get(String key) {
        ServiceAuthRegist serviceAuthRegist = authCache.get(key);
        return serviceAuthRegist;
    }


    /**
     * 获取指定服务的无需授权登录的URL 列表
     *
     * @return
     */
    public List<String> getIgnoreAuthPathList(String key) {
        List<String> allIgnoreList = new ArrayList<>(50);
        ServiceAuthRegist optionalServiceAuthRegist = get(key);
        if (optionalServiceAuthRegist != null) {
            allIgnoreList.addAll(optionalServiceAuthRegist.getIgnoreAuthList());
        }
        return allIgnoreList;
    }


    /**
     * 获取指定服务的的黑名单
     *
     * @return
     */
    public List<String> getUrlBlacklist(String key) {
        List<String> urlBlackList = new ArrayList<>(50);
        ServiceAuthRegist optionalServiceAuthRegist = get(key);
        if (optionalServiceAuthRegist != null) {
            urlBlackList.addAll(optionalServiceAuthRegist.getUrlBlacklist());
        }
        return urlBlackList;
    }

    public void cache(String key, ServiceAuthRegist authRegist) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(key));
        Preconditions.checkNotNull(authRegist);
        authCache.put(key, authRegist);
    }


    /**
     * 初始化 JVM Cache
     */
    @Override
    public void afterPropertiesSet() {
        authCache = Caffeine.newBuilder()
                .expireAfterWrite(30, TimeUnit.SECONDS)
                .maximumSize(100)
                .build(key -> {
                    String rediskey = "gateway:auth:" + key;
                    if (!redisTemplate.hasKey(rediskey)) {
                        return null;
                    }
                    return JSON.parseObject(redisTemplate.opsForValue().get(rediskey), ServiceAuthRegist.class);
                });
    }
}
