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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

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

@Component
public class RoomCtxCache {
    @Autowired
    private StringRedisTemplate redisTemplate;

    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);
        redisTemplate.opsForHash().putIfAbsent(key,sessionKey,userType);
        redisTemplate.expire(key,7, TimeUnit.DAYS);
    }

    public List<String> getSessionKeysByRoomId(Long roomId){
        String key = getKey(roomId);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        List<String> res = new ArrayList<>();
        for (Object o : entries.keySet()) {
            res.add(String.valueOf(o));
        }
        return res;
    }

    public String getSessionKeyByRoomIdAndUserType(Long roomId,Integer userType){
        String key = getKey(roomId);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        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);
    }
}
