package ink.wgink.app.impl;

import ink.wgink.interfaces.manager.IAppTokenService;
import ink.wgink.pojo.app.AppToken;
import ink.wgink.pojo.app.AppTokenUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: DefaultAppTokenService
 * @Description: 默认app token 实现
 * @Author: wanggeng
 * @Date: 2021/11/30 2:05 下午
 * @Version: 1.0
 */
@Service
public class DefaultAppTokenServiceImpl implements IAppTokenService {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultAppTokenServiceImpl.class);

    private static final Map<String, AppToken> tokens = new ConcurrentHashMap();

    @Override
    public AppToken getToken(String token) {
        AppToken appToken = tokens.get(token);
        if (appToken != null) {
            appToken.setLastTime(System.currentTimeMillis());
        }
        return appToken;
    }

    @Override
    public void addToken(String token, AppToken.AppTokenTypeEnum appTokenTypeEnum, AppTokenUser appTokenUser) {
        AppToken appToken = new AppToken();
        appToken.setToken(token);
        appToken.setAppTokenTypeEnum(appTokenTypeEnum);
        appToken.setLastTime(System.currentTimeMillis());
        appToken.setAppTokenUser(appTokenUser);
        appToken.setUserId(appTokenUser.getId());
        for (Map.Entry<String, AppToken> kvs : tokens.entrySet()) {
            if (StringUtils.equals(appTokenUser.getId(), kvs.getValue().getUserId())) {
                tokens.remove(kvs.getValue().getToken());
                break;
            }
        }
        tokens.put(token, appToken);
    }

    @Override
    public List<AppTokenUser> listCurrentUsers() {
        List<AppTokenUser> users = new ArrayList<>();
        for (Map.Entry<String, AppToken> kvs : tokens.entrySet()) {
            AppToken appToken = kvs.getValue();
            users.add(appToken.getAppTokenUser());
        }
        return users;
    }

    @Override
    public void clearTimeoutToken() {
        long currentTime = System.currentTimeMillis();
        List<String> clearTokenKeys = new ArrayList<>(0);
        for (Map.Entry<String, AppToken> kvs : tokens.entrySet()) {
            AppToken appToken = kvs.getValue();
            // 超过10分钟
            if (currentTime - appToken.getLastTime() > 600000L) {
                clearTokenKeys.add(kvs.getKey());
            }
        }
        for (String tokenKey : clearTokenKeys) {
            tokens.remove(tokenKey);
        }
        LOG.trace("本次共清理超时Token:{}个", clearTokenKeys.size());
    }
}
