package com.lightinit.hsdatagateway.common.utils.model;

import com.lightinit.hsdatagateway.common.utils.CacheUtils;
import com.lightinit.hsdatagateway.common.utils.SpringContextHolder;
import com.lightinit.hsdatagateway.modules.gateway.entity.BlackWhiteList;
import com.lightinit.hsdatagateway.modules.gateway.service.BlackWhiteListService;
import com.lightinit.hsdatagateway.modules.gateway.entity.BlackWhiteList;
import lombok.Data;

import java.util.Objects;

/**
 * @Author: yangrui
 * @Date: 2019/3/5 17:15
 */
@Data
public class CacheModel {

    public Integer frequency;

    public long timestamp;

    private static BlackWhiteListService service = SpringContextHolder.getBean(BlackWhiteListService.class);

    public boolean verifyIpFrequency(String ip){
        CacheModel ipCache = (CacheModel)CacheUtils.get("ipCache", ip);
        long now = System.currentTimeMillis();
        if (Objects.isNull(ipCache)){
            ipCache = new CacheModel();
            ipCache.setTimestamp(now);
            ipCache.setFrequency(1);
            CacheUtils.put("ipCache", ip, ipCache);
        }else {
            long difference = now - ipCache.getTimestamp();
            if (difference <= 1000){
                Integer frequency = ipCache.getFrequency();
                if (++frequency < 500){

                    ipCache.setFrequency(frequency);
                    CacheUtils.put("ipCache",ip, ipCache);
                }else {
                    BlackWhiteList blackWhiteList = new BlackWhiteList();
                    blackWhiteList.setListType("黑名单");
                    blackWhiteList.setIp(ip);
                    service.save(blackWhiteList);
                    CacheUtils.remove("ipCache", ip);
                    return false;
                }
            }else {
                ipCache.setFrequency(1);
                ipCache.setTimestamp(now);
                CacheUtils.put("ipCache", ip, ipCache);
            }
        }
        return true;
    }


}
