package com.ruoyi.cai.ws.cache;

import com.ruoyi.cai.ws.constant.RedisConstant;
import org.apache.commons.lang3.BooleanUtils;
import org.redisson.api.RMap;
import org.redisson.api.RScript;
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.Collections;
import java.util.Map;

@Component
public class CallerRoomCache {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    public String getKey(Long fromUserId){
        return String.format(RedisConstant.CALLER_ROOM_DATA,fromUserId);
    }

    public Long getRoomId(Long fromUserId, Long toUserId){
        String key = getKey(fromUserId);
        RMap<String, Object> map = redissonClient.getMap(key);
        Object roomId = map.get(toUserId+"");
        return roomId == null ? null : Long.valueOf(roomId.toString());
    }

    public void addRoom(Long fromUid, Long toUid, Long roomId) {
        String key = getKey(fromUid);
        RMap<String, Object> map = redissonClient.getMap(key);
        map.put(toUid+"",roomId+"");
        map.expire(Duration.ofDays(7));
//        map.expire(7,TimeUnit.DAYS);
//        redisTemplate.opsForHash().put(key,toUid,roomId);
//        redisTemplate.expire(key,7, TimeUnit.DAYS);
    }

    public Map<Object,Object> getAll(Long fromUid){
        String key = getKey(fromUid);
        RMap<Object, Object> map = redissonClient.getMap(key);
        return map.readAllMap();
//        return redisTemplate.opsForHash().entries(key);
    }

    public void del(Long fromUid) {
        String key = getKey(fromUid);
        redissonClient.getMap(key).delete();
    }

    private final static String DEL_ROOM_LUA =
            "local r = tonumber(redis.call('hget',KEYS[1],ARGV[1]))\n" +
            "if r == tonumber(ARGV[2]) then\n" +
            "   return redis.call('hdel',KEYS[1],ARGV[1])\n" +
            "end\n" +
            "return 0";

    public boolean delRoom(Long callerId, Long receiverId, Long roomId) {
        RScript script = redissonClient.getScript();
        Boolean execute = script.eval(RScript.Mode.READ_WRITE, DEL_ROOM_LUA, RScript.ReturnType.BOOLEAN,
                Collections.singletonList(getKey(callerId)), receiverId+"", roomId+"");
//        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(DEL_ROOM_LUA,Boolean.class);
//        Boolean execute = redisTemplate.execute(redisScript, Collections.singletonList(getKey(roomId)), receiverId,roomId);
        return BooleanUtils.isTrue(execute);
    }
}
