package security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.StringUtil;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Created by sunhao on 17/3/3.
 */
@Service
public class RedisLoginStatusManagerImpl implements RedisLoginStatusManager {

    protected int tokenExpireSeconds = 7 * 24 * 3600;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * Redis中记录login密码的Token的前缀
     */
    private static final String REDIS_LOGIN_PREFIX = "LOGIN_STATUS_TOKEN_";

    @Override
    public void createLoginStatus(String token, String pwd) {

        String formatToken = formatKey(token);
        String loginStatus = getLoginPassword(formatToken);

        if(!StringUtil.isEmpty(loginStatus)) {
            delete(formatToken);
        }

        set(formatToken,pwd,tokenExpireSeconds);
    }

    @Override
    public void deleteLoginStatus(String token) {
        delete(formatKey(token));
    }

    @Override
    public boolean getLoginStatusByKey(String token) {

        String pwd = getLoginPassword(token);

        return !StringUtil.isEmpty(pwd);

    }

    @Override
    public String getLoginPassword(String token) {

        String pwd = get(formatKey(token));
        //每次取的时候重置失效时间
        if(!StringUtil.isEmpty(pwd)) {

            expire(formatKey(token), tokenExpireSeconds);
        }

        return pwd;
    }


    private String formatKey(String token) {
        return REDIS_LOGIN_PREFIX.concat(token);
    }


    /**
     * 取redis
     */
    private String get(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 存redis
     */
    private String set(String key, String value, int expireSeconds) {

        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, expireSeconds, TimeUnit.SECONDS);

        return value;
    }

    /**
     * 设置过期时间
     */
    private void expire(String key, int seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    /**
     * 删除redis记录
     */
    private void delete(String... keys) {
        redisTemplate.delete(Arrays.asList(keys));
    }
}
