package redismgr

import (
	"encoding/json"
	"server/game/room"

	"github.com/gomodule/redigo/redis"
	"github.com/name5566/leaf/log"
)

// 保存房间的基础信息和玩家信息到 Redis（去掉 GameRound 和 RoundSitPos）
func SaveRoomToRedis(roomInfo *room.Room) error {
	// 获取 Redis 连接
	conn := GetPool().Get()
	defer conn.Close()

	// 将房间的基础信息（不包含 GameRound 和 RoundSitPos）序列化为 JSON
	roomJson, err := json.Marshal(roomInfo)
	if err != nil {
		log.Debug("Error marshalling room data: %v", err)
		return err
	}

	// 使用 HSET 存储房间的 JSON 字符串
	_, err = conn.Do("HSET", "teem_patti:"+roomInfo.Id, "RoomData", string(roomJson))
	if err != nil {
		log.Debug("Error saving room data to Redis: %v", err)
		return err
	}

	// 设置房间的过期时间为 3 天
	_, err = conn.Do("EXPIRE", "teem_patti:"+roomInfo.Id, 86400*3) // 86400*3 = 3 天
	if err != nil {
		log.Debug("Error setting expiry for room data in Redis: %v", err)
		return err
	}

	log.Debug("Room data saved to Redis for roomId: %s", roomInfo.Id)
	return nil
}

func GetRoomFromRedis(roomId string) (*room.Room, error) {
	// 获取 Redis 连接
	conn := GetPool().Get()
	defer conn.Close()

	// 获取房间的 JSON 字符串
	roomData, err := redis.String(conn.Do("HGET", "teem_patti:"+roomId, "RoomData"))
	if err != nil {
		log.Debug("Error fetching room data from Redis: %v", err)
		return nil, err
	}

	// 反序列化 JSON 字符串为 Room 结构体
	var room room.Room
	err = json.Unmarshal([]byte(roomData), &room)
	if err != nil {
		log.Debug("Error unmarshalling room data: %v", err)
		return nil, err
	}

	// 返回房间数据
	return &room, nil
}
func IsRoomExistInRedis(roomId string) (bool, error) {
	// 获取 Redis 连接
	conn := GetPool().Get()
	defer conn.Close()

	// 检查房间 ID 是否存在于 Redis 集合中
	exists, err := redis.Bool(conn.Do("SISMEMBER", "teen_patti_rooms", roomId))
	if err != nil {
		log.Debug("Error checking if roomId exists in teen_patti_rooms: %v", err)
		return false, err
	}

	return exists, nil
}

func SaveRoomIDToRedis(roomId string) error {
	// 获取 Redis 连接
	conn := GetPool().Get()
	defer conn.Close()

	// 检查房间 ID 是否已经存在于集合中
	exists, err := redis.Bool(conn.Do("SISMEMBER", "teen_patti_rooms", roomId))
	if err != nil {
		log.Debug("Error checking if roomId exists in teen_patti_rooms: %v", err)
		return err
	}

	if exists {
		log.Debug("Room ID %s already exists in teen_patti_rooms", roomId)
		return nil // 如果房间 ID 已存在，直接返回
	}

	// 将房间 ID 存储到 Redis 集合中
	_, err = conn.Do("SADD", "teen_patti_rooms", roomId)
	if err != nil {
		log.Debug("Error adding roomId to teen_patti_rooms: %v", err)
		return err
	}

	log.Debug("Room ID %s added to teen_patti_rooms", roomId)
	return nil
}

func RemoveRoomIDFromRedis(roomId string) error {
	// 获取 Redis 连接
	conn := GetPool().Get()
	defer conn.Close()

	// 从 Redis 集合中删除房间 ID
	_, err := conn.Do("SREM", "teen_patti_rooms", roomId)
	if err != nil {
		log.Debug("Error removing roomId from teen_patti_rooms: %v", err)
		return err
	}

	log.Debug("Room ID %s removed from active_rooms", roomId)
	return nil
}
