package com.sonic.bear.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.base.Strings;
import com.sonic.bear.dao.AppClientDao;
import com.sonic.bear.domain.entity.AppClient;
import com.sonic.bear.service.AppClientService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author coder
 */
@Service
public class AppClientServiceImpl extends ServiceImpl<AppClientDao, AppClient> implements AppClientService, InitializingBean {

    LoadingCache<String, Map<String, AppClient>> appClientCache;

    @Override
    public Optional<AppClient> getByCode(String code) {
        if (Strings.isNullOrEmpty(code)) {
            return Optional.empty();
        }

        Map<String, AppClient> codeAppClientMap = appClientCache.get("");
        if (codeAppClientMap == null) {
            return Optional.empty();
        }

        return Optional.ofNullable(codeAppClientMap.get(code));
    }

    @Override
    public void afterPropertiesSet() {
        appClientCache = Caffeine.newBuilder()
                .maximumSize(20)
                .initialCapacity(5)
                .recordStats()
                //缓存24小时
                .expireAfterWrite(Duration.ofSeconds(24 * 60 * 60))
                .build(key -> baseMapper.selectList(null).stream()
                        .collect(Collectors.toMap(AppClient::getCode, Function.identity())));
    }
}
