package com.yingying.tourist.request;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class SessionAuthorization implements InitializingBean {
	public static final String SESSION_KEY_COOKIE_NAME = "jituan";
	public static final int DEFAULT_SESSION_COOKIE_EXPIRE = 604800; // 604800 604800
	public static final String SESSION_KEY_PREFIX = "WeChatToken";
	
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	
	private static RedisTemplate<Object, Object> baseRedisTemplate;
	
	public static void setSession(String token) {
		ValueOperations<Object, Object> ops = baseRedisTemplate.opsForValue();
		ops.set(SESSION_KEY_PREFIX + ":" + RequestSessionKey.getSessionKey(), token, DEFAULT_SESSION_COOKIE_EXPIRE, TimeUnit.SECONDS);
	}
	
	public static Integer getSession() {
		ValueOperations<Object, Object> ops = baseRedisTemplate.opsForValue();
		Integer sessionValue = (Integer) ops.get(SESSION_KEY_PREFIX + ":" + RequestSessionKey.getSessionKey());
		
		return sessionValue;
	}
	
	public static void removeSession() {
		baseRedisTemplate.delete(SESSION_KEY_PREFIX + ":" + RequestSessionKey.getSessionKey());
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		baseRedisTemplate = this.redisTemplate;
	}
	
}
