package xyz.wbsite.frame.provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.wbsite.config.CacheConfig;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.base.UserEntity;
import xyz.wbsite.frame.utils.IDgenerator;

import javax.validation.constraints.NotNull;

@Component
public class SimpleTokenProvider implements TokenProvider {

    @Autowired
    private CacheConfig cacheConfig;

    public Token build(@NotNull UserEntity userEntity) {
        Token token = new Token();
        token.setId(IDgenerator.nextId());
        token.setUserId(userEntity.getId());
        token.setToken(IDgenerator.nextUUID());
        token.setUserName(userEntity.getUserName());
        token.setUserAlias(userEntity.getUserAlias());
        token.putRes(userEntity.getResSet());
        cacheConfig.put(token.getToken(), token, 3 * 60 * 60 * 1000);
        return token;
    }

    public Token build(@NotNull String token) {
        // 检索缓存Token
        Object o = cacheConfig.get(token);
        if (o != null && o instanceof Token) {
            return (Token) o;
        }
        return null;
    }
}
