/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.core.cache;

import com.crunii.micro.common.constants.RedisKeys;
import com.crunii.micro.domain.entity.main.TsmUrl;
import com.crunii.micro.domain.repo.main.TsmUrlRepo;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author shenhs create 2023/5/23 15:27
 */
@Slf4j
@Component
public class TsmURLCache implements InitializingBean {

	@Autowired
	private RedissonClient redisson;
	@Autowired
	private TsmUrlRepo repo;

	private RMapCache<Integer, TsmUrl> urlRMapCache = null;
	// 这个Map的数据15秒内会过期
	private Cache<Integer, TsmUrl> timedCache = CacheBuilder.newBuilder().expireAfterWrite(20, TimeUnit.SECONDS).build();

	@Override public void afterPropertiesSet() throws Exception {
		if(urlRMapCache==null){
			urlRMapCache = redisson.getMapCache(RedisKeys.TSM_URL_CACHE_KEY);
		}
		if(urlRMapCache.isEmpty()){
			load();
		}
	}

	public void load(){
		List<TsmUrl> all = repo.findAll();
		Map<Integer, TsmUrl> collect = all.parallelStream().collect(Collectors.toMap(TsmUrl::getUrlId, Function.identity()));
		urlRMapCache.putAll(collect);
		log.info("加载tsm_url缓存【{}】条",urlRMapCache.size());
	}

	public TsmUrl get(Integer id){
		TsmUrl o = timedCache.getIfPresent(id);
		if(o==null){
			Map<Integer, TsmUrl> collect = urlRMapCache.values().parallelStream().collect(Collectors.toMap(TsmUrl::getUrlId, Function.identity()));
			timedCache.putAll(collect);
			return timedCache.getIfPresent(id);
		}
		return o;
	}

	public void reload(){
		urlRMapCache.clear();
		load();
	}
}
