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

import cn.com.duiba.tuia.activity.center.api.remoteservice.RemoteSystemConfigService;
import com.duiba.tuia.youtui.web.service.SystemConfigService;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
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.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 处理系统配置的service
 * @author lichao 2018/4/20
 */
@Service
public class SystemConfigServiceImpl implements SystemConfigService ,InitializingBean {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RemoteSystemConfigService remoteSystemConfigService;

    /** 系统配置缓存 */
    private LoadingCache<String,Optional<String>> sysConfigCache;

    @Override
    public void afterPropertiesSet() throws Exception {
        sysConfigCache = CacheBuilder
                .newBuilder()
                .maximumSize(100)
                .refreshAfterWrite(10, TimeUnit.MINUTES)
                .build(new CacheLoader<String, Optional<String>>() {

                    @Override
                    public Optional<String> load(String key) throws Exception {
                        return Optional.ofNullable(getSystemConfigNative(key));
                    }
                });
    }

    @Override
    public String getSystemConfig(String key) {

        try {
            Optional<String> s = this.sysConfigCache.get(key);
            return s.orElse(null);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }

    }

    /**
     * 不走本地缓存
     *
     * @param key
     */
    @Override
    public String getSystemConfigNative(String key) {
        return remoteSystemConfigService.selectByKey(key).getResult();
    }

}
