package com.gitee.sop.admin.service.sys.impl;

import com.gitee.sop.admin.common.user.User;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.dao.entity.SysUser;
import com.gitee.sop.admin.service.sys.SysUserService;
import com.gitee.sop.admin.service.sys.UserCacheService;
import com.gitee.sop.admin.service.sys.dto.SysUserDTO;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author 六如
 */
public class LocalUserCacheService implements UserCacheService {

    @Autowired
    private SysUserService sysUserService;

    // key: configKey, value: configValue
    private final LoadingCache<Long, Optional<User>> configCache = CacheBuilder.newBuilder()
            .expireAfterAccess(30, TimeUnit.MINUTES)
            .build(new CacheLoader<Long, Optional<User>>() {
                @Override
                public Optional<User> load(Long key) throws Exception {
                    return Optional.ofNullable(loadFromDb(key));
                }
            });

    @Override
    public Optional<User> getUser(Long userId) {
        return configCache.getUnchecked(userId);
    }

    private User loadFromDb(Long userId) {
        SysUser sysUser = sysUserService.getById(userId);
        return CopyUtil.copyBean(sysUser, SysUserDTO::new);
    }

    @PostConstruct
    public void init() {
        List<SysUser> sysUsers = sysUserService.listAll();
        List<SysUserDTO> sysUserDTOS = CopyUtil.copyList(sysUsers, SysUserDTO::new);
        for (SysUserDTO sysUserDTO : sysUserDTOS) {
            configCache.put(sysUserDTO.getUserId(), Optional.of(sysUserDTO));
        }
    }

}
