package com.tmerclub.cloud.common.util;

import jakarta.websocket.Session;

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

/**
 * @author TRACK
 */
public class MapUtil {

    /**
     * map中是否存在key
     * @param map
     * @param keyPrefix key前缀
     * @return
     */
    public static Boolean isExistKeyPrefix(ConcurrentHashMap<String, Session> map, String keyPrefix) {
        for (String key : map.keySet()) {
            if (key.startsWith(keyPrefix)) {
                return true;
            }
        }
        return false;
    }

    /**
     * map中含有key前缀的会话列表集合
     * @param map
     * @param keyPrefix key前缀
     * @return
     */
    public static List<Session> getSessionByKeyPrefix(ConcurrentHashMap<String, Session> map, String keyPrefix) {
        List<Session> sessionList = new ArrayList<>();
        for (String key : map.keySet()) {
            if (key.startsWith(keyPrefix)) {
                sessionList.add(map.get(key));
            }
        }
        return sessionList;
    }

    /**
     * map中含有key前缀的key列表集合
     * @param map
     * @param keyPrefix key前缀
     * @return
     */
    public static List<String> getKeysByKeyPrefix(ConcurrentHashMap<String, Session> map, String keyPrefix) {
        List<String> keys = new ArrayList<>();
        for (String key : map.keySet()) {
            if (key.startsWith(keyPrefix)) {
                keys.add(key);
            }
        }
        return keys;
    }

    /**
     * map中含有keyPrefix并且不包括key的集合
     * @param map
     * @param keyPrefix key前缀
     * @param excludeKey 排除该key
     * @return
     */
    public static List<String> getKeysByPrefixAndExcludeKey(ConcurrentHashMap<String, Session> map, String keyPrefix, String excludeKey) {
        List<String> keys = new ArrayList<>();
        for (String key : map.keySet()) {
            if (key.startsWith(keyPrefix) && !Objects.equals(excludeKey, key)) {
                keys.add(key);
            }
        }
        return keys;
    }
}
