package com.uas.account.dao;

import java.io.Serializable;

import org.apache.shiro.dao.DataAccessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.uas.account.entity.Token;

@Repository
public class TokenDaoImpl implements TokenDao {

	@Autowired
	private RedisTemplate<Serializable, Serializable> redisTemplate;

	@Override
	public void save(final Token token) {
		redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException {
				byte[] key = redisTemplate.getStringSerializer().serialize("AccessToken.id." + token.getId());
				byte[] value = redisTemplate.getStringSerializer().serialize(JSON.toJSONString(token));
				connection.set(key, value);
				connection.expire(key, token.getExpires_in());
				return null;
			}
		});
	}

	@Override
	public Token findOne(final String id) {
		return redisTemplate.execute(new RedisCallback<Token>() {
			@Override
			public Token doInRedis(RedisConnection connection) throws DataAccessException {
				byte[] key = redisTemplate.getStringSerializer().serialize("AccessToken.id." + id);
				if (connection.exists(key)) {
					String value = redisTemplate.getStringSerializer().deserialize(connection.get(key));
					return JSON.parseObject(value, Token.class);
				}
				return null;
			}
		});
	}

	@Override
	public void delete(final String id) {
		redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection) throws DataAccessException {
				byte[] key = redisTemplate.getStringSerializer().serialize("AccessToken.id." + id);
				connection.del(key);
				return null;
			}
		});
	}

}
