package com.ruoyi.cai.ws.cache;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.cai.ws.bean.UserData;
import com.ruoyi.cai.ws.constant.RedisConstant;
import com.ruoyi.cai.ws.constant.UserDataConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

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

    public String getKey(Long roomId,int type){
        return String.format(RedisConstant.USER_ROOM_DATA,roomId,type== UserDataConstant.TYPE_CALLER?"caller":"receiver");
    }

    public UserData getCallerUserDataByRoom(Long roomId){
        return getUserDataByRoom(roomId,UserDataConstant.TYPE_CALLER);
    }

    public UserData getReceiverUserDataByRoom(Long roomId){
        return getUserDataByRoom(roomId,UserDataConstant.TYPE_RECEIVER);
    }

    public UserData getUserDataByRoom(Long roomId,int type){
        String key = getKey(roomId, type);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        if(entries.get("roomId") == null){
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(entries),UserData.class);
    }

    public void init(UserData userData,int type){
        String key = getKey(userData.getRoomId(), type);
        userData.setUserType(type);
        Map<String,Object> map = JSON.parseObject(JSON.toJSONString(userData));
        redisTemplate.opsForHash().putAll(key,map);
    }

    public void initCaller(UserData callerUserData) {
        init(callerUserData,UserDataConstant.TYPE_CALLER);
    }

    public void initReceiver(UserData callerUserData) {
        init(callerUserData,UserDataConstant.TYPE_RECEIVER);
    }

    public void hMSet(Long roomId,Integer userType,Map<String,Object> data) {
        String key = getKey(roomId, userType);
        redisTemplate.opsForHash().putAll(key,data);
    }
}
