package com.uas.platform.b2b.redis.dao.impl;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
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.uas.platform.core.util.serializer.FlexJsonUtils;
import com.uas.platform.b2b.model.AccessToken;
import com.uas.platform.b2b.redis.dao.AccessTokenDao;

@Repository
public class AccessTokenDaoImpl implements AccessTokenDao {

	@Autowired
	private RedisTemplate<Serializable, Serializable> redisTemplate;

	@Override
	public void save(final AccessToken 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(FlexJsonUtils.toJson(token));
				connection.set(key, value);
				connection.expire(key, token.getExpires_in());
				return null;
			}
		});
	}

	@Override
	public AccessToken findOne(final String id) {
		return redisTemplate.execute(new RedisCallback<AccessToken>() {
			@Override
			public AccessToken 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 FlexJsonUtils.fromJson(value, AccessToken.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;
			}
		});
	}

}
