package com.cm.common.wechat.manager.miniapp;

import com.cm.common.wechat.config.pojo.WechatMiniAppProperties;
import com.cm.common.wechat.pojo.WechatMiniAppUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: WechatMiniAppManager
 * @Description: 微信小程序管理
 * @Author: WangGeng
 * @Date: 2020/5/9 18:05
 * @Version: 1.0
 **/
public class WechatMiniAppManager {

    private static final Logger LOG = LoggerFactory.getLogger(WechatMiniAppManager.class);
    private static WechatMiniAppManager wechatMiniAppManager = WechatMiniAppManagerBuilder.wechatMiniAppManager;
    // 超时分钟
    private final int TIME_OUT_SECOND = 120 * 60;
    private WechatMiniAppProperties wechatMiniAppProperties;

    private WechatMiniAppManager() {
    }

    private Map<String, WechatMiniAppUserInfo> users = new ConcurrentHashMap<>();

    public static WechatMiniAppManager getInstance() {
        return wechatMiniAppManager;
    }

    /**
     * 添加用户
     *
     * @param token
     * @param wechatMiniAppUserInfo
     */
    public void addUser(String token, WechatMiniAppUserInfo wechatMiniAppUserInfo) {
        wechatMiniAppUserInfo.setUpdateTime(System.currentTimeMillis());
        users.put(token, wechatMiniAppUserInfo);
    }

    /**
     * 获取小程序应用
     *
     * @param token
     * @return
     */
    public WechatMiniAppUserInfo getWechatMiniAppUserInfoByToken(String token) {
        return users.get(token);
    }

    /**
     * 删除超时用户
     */
    public void removeTimeoutUser() {
        LOG.debug("delete timeout wechat mini app user start");
        long startTime = System.currentTimeMillis();
        List<String> tokenList = new ArrayList<>();
        for (Map.Entry<String, WechatMiniAppUserInfo> kv : users.entrySet()) {
            // 超时
            if ((startTime - kv.getValue().getUpdateTime()) / 1000 > TIME_OUT_SECOND) {
                tokenList.add(kv.getKey());
            }
        }
        for (String token : tokenList) {
            users.remove(token);
        }
        long endTime = System.currentTimeMillis();
        LOG.debug("delete timeout wechat mini app user end, delete count: {}, useTime: {}ms", tokenList.size(), endTime - startTime);
    }

    public void setWechatMiniAppProperties(WechatMiniAppProperties wechatMiniAppProperties) {
        this.wechatMiniAppProperties = wechatMiniAppProperties;
    }

    private static class WechatMiniAppManagerBuilder {
        public static final WechatMiniAppManager wechatMiniAppManager = new WechatMiniAppManager();
    }
}
