package com.duiba.tuia.youtui.web.service.impl;

import cn.com.duiba.tuia.activity.center.api.constant.ConfigKey;
import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteSystemConfigService;
import com.duiba.tuia.youtui.web.service.MengMaService;
import com.duiba.tuia.youtui.web.tool.APIUtils;
import com.duiba.tuia.youtui.web.tool.QpsLimit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class MengMaServiceImpl implements MengMaService,InitializingBean {

    private QpsLimit qpsLimit;

    private static final int DEFAULT_LIMIT_TIMES = 8;
    private static final int UN_LIMIT = -1;
    private static final int ZERO_LIMIT = 0;

    @Autowired
    private RemoteSystemConfigService remoteSystemConfigService;

    private LoadingCache<String,Integer> limitTimesCache;

    private static final Logger log = LoggerFactory.getLogger(MengMaServiceImpl.class);

    private static final String KEY = "mengma";

    @Override
    public void afterPropertiesSet() throws Exception {
        qpsLimit = QpsLimit.builder();
        limitTimesCache = CacheBuilder
                .newBuilder()
                .refreshAfterWrite(1, TimeUnit.MINUTES)
                .build(new CacheLoader<String, Integer>() {
                    @Override
                    public Integer load(String s) throws Exception {
                        return getLimitTimes();
                    }
                });

    }

    @Override
    public String getTick(boolean isIncrementQps) {

        int limit = getQpsLimit();
        if (UN_LIMIT == limit) {
            return APIUtils.getTick();
        }
        if (ZERO_LIMIT == limit) {
            return "";
        }
        //猛犸事件，每台qps 限制8，总的限制48
        return this.qpsLimit.isQpsLimit(KEY, getQpsLimit(), isIncrementQps) ? APIUtils.getTick() : "";
    }

    @Override
    public int getQpsLimit() {
        try {
            return limitTimesCache.get("key");
        } catch (ExecutionException e) {
            log.error("", e);
            return DEFAULT_LIMIT_TIMES;
        }
    }

    @Override
    public void setQpsLimit(int times) {
        this.remoteSystemConfigService.configByKey(ConfigKey.MENGMA_QPS_LIMIT_TIMES, String.valueOf(times));
    }

    @Override
    public void incrementQps() {
        int limit = getQpsLimit();
        if (limit > 0) {
            this.qpsLimit.incrementQps(KEY);
        }

    }

    private int getLimitTimes() {
        String value = this.remoteSystemConfigService.selectByKey(ConfigKey.MENGMA_QPS_LIMIT_TIMES.getKey()).getResult();
        if (StringUtils.isNumeric(value)) {
            return Integer.valueOf(value);
        }
        return DEFAULT_LIMIT_TIMES;//无配置的情况下，默认8
    }
}
