package com.games.gateway.filters;

import com.games.gateway.enums.BizResultCode;
import com.games.gateway.config.FilterOrderedConfig;
import com.games.gateway.config.GatewayBizConfig;
import com.games.gateway.enums.LimiterTypeEnum;
import com.games.gateway.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 路径 限流器
 */
@Order(FilterOrderedConfig.PathLimitGlobalFilter)
@Slf4j
@Component
public class PathLimitGlobalFilter implements GlobalFilter {

    @Autowired
    private GatewayBizConfig globalConfig;

    @Autowired
    private LimitUtils limitUtils;

    @Autowired
    private PathWhiteCache pathWhiteCache;

    @Autowired
    private LimitCache limitCache;

    @Autowired
    private RedisKeyUtils redisKeyUtils;


    /**
     * 限制缓存过期时间,秒
     */
    private static Integer EXPIRE_TIME = 60;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();

        //白名单存在path，直接通过
        if (pathWhiteCache.exists(path)) {
            return chain.filter(exchange);
        }

        //application全局设置速率
        Integer pathLimiterNum = globalConfig.getPathLimiter();

        //mock接口单独对path设置了速率
        Integer pathLimiter = limitCache.get(LimiterTypeEnum.PATH, path);
        if (pathLimiter > 0) {
            pathLimiterNum = pathLimiter;
        }
        //检测是否超过最大访问次数
        String limitKey = redisKeyUtils.pathLimitCheckKey(path);
        boolean b = limitUtils.limitCheck(limitKey, pathLimiterNum, EXPIRE_TIME);
        if (b) {
            log.info("path:{} limited", path);
            //设置locale
            MessageUtils.setLocale(exchange);
            BizResultCode.SYS_OPERATOR_FAST_ERROR.check(true);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
}
