package com.diaoyun.zion.master.common;

import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.config.DomainProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单实例环境令牌管理
 * 
 * @author Joe
 */
@Component("localTokenManager")
public class LocalTokenManager extends TokenManager {

	private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DomainProperties domainProperties;

	// 令牌存储结构 TODO 放到 redis 中
	private final ConcurrentHashMap<String, DummyUser> tokenMap = new ConcurrentHashMap<String, DummyUser>();

	@Override
	public void verifyExpired() {
		Date now = new Date();
		for (Entry<String, DummyUser> entry : tokenMap.entrySet()) {
			String token = entry.getKey();
			DummyUser dummyUser = entry.getValue();
			// 当前时间大于过期时间
			if (now.compareTo(dummyUser.expired) > 0) {
				// 已过期，清除对应token
				if (now.compareTo(dummyUser.expired) > 0) {
					tokenMap.remove(token);
					logger.debug("token : " + token + "已失效");
				}
			}
		}
	}

	public void addToken(String token, TbCfUserInfoVo loginUser) {
		DummyUser dummyUser = new DummyUser();
		dummyUser.loginUser = loginUser;
		extendExpiredTime(dummyUser);
		tokenMap.putIfAbsent(token, dummyUser);
	}

	public TbCfUserInfoVo validate(String token) {
		DummyUser dummyUser = tokenMap.get(token);
		if (dummyUser == null) {
			return null;
		}
		extendExpiredTime(dummyUser);
		return dummyUser.loginUser;
	}

	public void remove(String token) {
		tokenMap.remove(token);
	}

	/**
	 * 扩展过期时间
	 * 
	 * @param dummyUser
	 */
	private void extendExpiredTime(DummyUser dummyUser) {
        String expiredTime=domainProperties.getProperty("redis.token.expiredTime");
        Integer expired=1800;
        if(StringUtils.isNotBlank(expiredTime)) {
            expired=Integer.valueOf(expiredTime);
        }
		dummyUser.expired = new Date(new Date().getTime() + tokenTimeout * expired);
	}

	// 复合结构体，含loginUser与过期时间expried两个成员
	private class DummyUser {
		private TbCfUserInfoVo loginUser;
		private Date expired; // 过期时间
	}
}
