package com.ruoyi.cai.ws.cache;

import com.ruoyi.cai.ws.constant.RedisConstant;
import com.ruoyi.cai.ws.constant.UserDataConstant;
import com.ruoyi.cai.ws.holder.WebSocketSessionHolder;
import org.redisson.api.RMap;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * key : 房间号
 * value： { sessionKey ： 用户类型 }
 * <p>created on 2024/1/11 22:45</p>
 * @author duet
 */
@Component
public class RoomCtxCache {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    public String getKey(Long roomId){
        return String.format(RedisConstant.FDCTX_ROOM_DATA,roomId);
    }

    public void addFd(String sessionKey,Long roomId,Integer userType){
        String key = getKey(roomId);
        RMap<Object, Object> map = redissonClient.getMap(key);
        map.put(sessionKey,userType);
        map.expire(Duration.ofDays(7));
    }

    public List<String> getSessionKeysByRoomId(Long roomId){
        String key = getKey(roomId);
        RMap<String, Object> entries = redissonClient.getMap(key);
        Set<String> set = entries.readAllKeySet();
        List<String> keys = new ArrayList<>();
        for (String sessionKey : set) {
            if(WebSocketSessionHolder.existSession(sessionKey)){
                keys.add(sessionKey);
            }
        }
        return keys;
    }

    public String getSessionKeyByRoomIdAndUserType(Long roomId,Integer userType){
        String key = getKey(roomId);
        RMap<Object, Object> map = redissonClient.getMap(key);
        Map<Object, Object> entries = map.readAllMap();
        for (Map.Entry<Object, Object> entry : entries.entrySet()) {
            String sessionKey = String.valueOf(entry.getKey());
            Integer userTypeK = Integer.valueOf(entry.getValue().toString());
            if(WebSocketSessionHolder.existSession(sessionKey) && userTypeK.equals(userType)){
                return sessionKey;
            }
        }
        return null;
    }

    public String getSessionKeyReceiverByRoomId(Long roomId){
        return getSessionKeyByRoomIdAndUserType(roomId, UserDataConstant.TYPE_RECEIVER);
    }

    public String getSessionKeyCallerByRoomId(Long roomId){
        return getSessionKeyByRoomIdAndUserType(roomId, UserDataConstant.TYPE_CALLER);
    }

    public void del(Long roomId) {
        String key = getKey(roomId);
        redisTemplate.delete(key);
    }
}
