package com.inkasso.auth.interceptor;

import com.inkasso.adapter.bean.AbstractUser;
import com.inkasso.adapter.exception.ServiceException;
import com.inkasso.adapter.exception.enums.ExceptionEnum;
import com.inkasso.adapter.web.LoginUserHolder;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class RateLimiterInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    private final String redisMark = "rateLimiter:";

    @Value("${kafubao.rateLimiter}")
    private Integer number;

    @Value("${kafubao.limiterTime}")
    private Integer time;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object o){

        AbstractUser abstractUser = LoginUserHolder.get();
        if(abstractUser!=null){
            //需要进行限流操作
            String redisKey = redisMark+abstractUser.getId();
            Long count = redisTemplate.opsForValue().increment(redisKey,1);
            if(count==1){
                redisTemplate.expire(redisKey,time, TimeUnit.SECONDS);
            }
            if(count>number){
                throw new ServiceException(HttpStatus.SC_TOO_MANY_REQUESTS, ExceptionEnum.REQUEST_TOO_MUCH);
            }
        }
        return true;
    }
}
