package cn.hnthyy.thmz.service.impl.thmz;

import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.entity.thmz.Token;
import cn.hnthyy.thmz.mapper.thmz.TokenMapper;
import cn.hnthyy.thmz.service.thmz.TokenService;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TokenServiceImpl implements TokenService {
    @SuppressWarnings("all")
    @Autowired
    private TokenMapper tokenMapper;
    //token 缓存
    private Map<String,Token> catchMap = new HashMap<>();

    @Override
    public int saveToken(Token token) {
        int num=tokenMapper.insertToken(token);
        catchMap.put(token.getToken(),token);
        return num;
    }

    @Override
    public List<Token> queryAll() {
        return tokenMapper.selectAll();
    }

    @Override
    public void initCacheMap() {
        List<Token> tokens = queryAll();
        if(tokens!=null && tokens.size()>0){
            Date now = new Date();
            tokens.forEach(token -> {
                if(token!=null){
                    if(token.getDeadTime().before(now)){
                        tokenMapper.deleteById(token.getId());
                    }
                    catchMap.put(token.getToken(),token);
                }
            });
        }
    }

    @Override
    public Token queryFromCache(String token) {
        return catchMap.get(token);
    }

    @Override
    public void expiryToken(String token) {
        DecodedJWT decodedJWT=TokenUtil.parseJWT(token);
        Date now = new Date();
        if(decodedJWT.getExpiresAt().after(now)){
            Token tokenObject = new Token(token, decodedJWT.getExpiresAt(), new Date());
            saveToken(tokenObject);
        }
    }

    @Override
    public void refreshTokenCache() {
        Date now= new Date();
        Iterator<Map.Entry<String,Token>> it = catchMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,Token> entry = it.next();
            if(entry!=null){
                Token token = catchMap.get(entry.getKey());
                if(token!=null && token.getDeadTime().before(now)){
                    tokenMapper.deleteById(token.getId());
                    it.remove();
                }
            }
        }
    }
}
