package com.handong.smartservice.JwtAuth;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;


public class JwtTokenStoreMap implements JwtTokenStore {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    Map<Long, String> mapToken = new HashMap<>();
    Map<Long, Long> mapExpire = new HashMap<>();
    int removeExpireSkip = 0;
    
    public JwtTokenStoreMap() {
    }

    @Override
    public String get(Long gid) {
        return mapToken.get(gid);
    }

    @Override
    public void save(Long gid, String token, Long expireTime) {
        if (removeExpireSkip++ > 500) {
            removeExpireSkip = 0;

            long currTime = System.currentTimeMillis();
            Iterator<Map.Entry<Long, Long>> iterator = mapExpire.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, Long> entry = iterator.next();
                
                logger.info("JwtTokenStoreMap, save, expire = " + entry.getValue() + ", currTime = " + currTime);
                if (entry.getValue() < currTime) {
                    mapToken.remove(entry.getKey());
                    iterator.remove();
                    logger.info("remove refresh token : " + entry.getKey());
                }
            }
        }

        mapToken.put(gid, token);
        mapExpire.put(gid, System.currentTimeMillis() + expireTime);
    }

    @Override
    public void delete(Long gid) {
        mapToken.remove(gid);
        mapExpire.remove(gid);
    }
}

