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.apache.commons.lang3.StringUtils;
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.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.http.HttpStatus.BAD_GATEWAY;

/**
 * IP 限流器
 * https://github.com/oneone1995/blog/issues/13
 */
@Order(FilterOrderedConfig.IpLimitGlobalFilter)
@Slf4j
@Component
public class IpLimitGlobalFilter implements GlobalFilter {

    @Autowired
    private LimitUtils limitUtils;

    @Autowired
    private GatewayBizConfig globalConfig;

    @Autowired
    private LimitCache limitCache;

    @Autowired
    private RedisKeyUtils redisKeyUtils;

    @Autowired
    private IpBlackCache ipBlackCache;

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

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = IpAddressUtils.getIpAddress(request);
        //如果是ip黑名单，则不执行
        if (ipBlackCache.isBlack(ip)) {
            log.info("ip is black:{}", ip);
            exchange.getResponse().setStatusCode(BAD_GATEWAY);
            return exchange.getResponse().setComplete();
        }
        ip = StringUtils.isNotEmpty(ip) ? ip.replace(":", "-") : ip;

        //application全局设置速率
        Integer ipLimiterNum = globalConfig.getIpLimiter();

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

}
