package com.apobates.forum.utils.cache;

import com.apobates.forum.utils.Commons;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 抽像CubbyHole,一个带缓存的集合.可以使用内存,NoSQL数据库来实现避免写的频繁
 * 
 * @param <T>
 * @author xiaofanku
 * @since 20200726
 */
public abstract class AbstractCubbyHole<T> {
	private final static Logger logger = LoggerFactory.getLogger(AbstractCubbyHole.class);
	
	/**
	 * 保存对象
	 * 
	 * @param value
	 * @return
	 */
	public abstract boolean put(final T value);

	/**
	 * 保存对象
	 * 
	 * @param values
	 */
	public abstract void putAll(final Collection<T> values);

	/**
	 * 返回对象的MD5签名
	 * 
	 * @param <T>
	 * @param obj
	 * @return
	 */
	public static <T> String toChecksum(T obj) {
		if (null == obj) {
			return "";
		}
		return generateUnionKey(introspect(obj));
	}

	private static <T> Map<String, Object> introspect(T obj) {
		try {
			return Commons.introspect(obj);
		} catch (Exception e) {
			if (logger.isDebugEnabled()) {
				logger.debug("获取Bean的属性信息出错", e);
			}
			e.printStackTrace();
		}
		return Collections.emptyMap();
	}

	private static String generateUnionKey(Map<String, Object> data) {
		if (null == data || data.isEmpty()) {
			return "";
		}
		try {
			String v = data.entrySet().stream().filter(entry -> !entry.getKey().toLowerCase().equalsIgnoreCase("id") && entry.getValue() != null && Commons.isNotBlank(entry.getValue().toString())).map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining(","));
			String key = Commons.md5(v);
			logger.info("[CH][Abs]"+v+",key="+key);
			return key;
		} catch (NullPointerException e) {
			if (logger.isDebugEnabled()) {
				logger.debug("生成对象的唯一可用值失败", e);
			}
			e.printStackTrace();
		}
		return "";
	}
}
