package robot.mj;

import com.taurus.core.entity.ITObject;
import com.taurus.core.plugin.redis.Redis;
import redis.clients.jedis.Jedis;
import taurus.client.TaurusClient;
import taurus.client.business.AccountBusiness;
import taurus.client.business.GroupRoomBusiness;

import java.util.HashMap;
import java.util.Map;

/**
 * 机器人连接管理器 - 管理与game_mj_cs的连接
 */
public class RobotConnectionManager {
    
    private static RobotConnectionManager instance;
    private Map<String, CSMJHandler> gameHandlers; // 按房间ID存储处理器
    private TaurusClient client;
    
    private RobotConnectionManager() {
        gameHandlers = new HashMap<>();
    }
    
    public static synchronized RobotConnectionManager getInstance() {
        if (instance == null) {
            instance = new RobotConnectionManager();
        }
        return instance;
    }
    
    /**
     * 连接到长沙麻将游戏服务器
     */
    public boolean connectToGameServer(String host, int port, int playerId, int groupId, String roomId) {
        try {
            // 创建长沙麻将AI处理器
            CSMJHandler handler = new CSMJHandler();
            
            // 连接到游戏服务器
            boolean connected = handler.connectToGameServer(host, port);
            if (!connected) {
                System.err.println("连接到游戏服务器失败: " + host + ":" + port);
                return false;
            }
            
            // 设置静态变量
            CSMJHandler.playerId = playerId;
            CSMJHandler.groupId = groupId;
            CSMJHandler.roomId = roomId;
            
            // 存储处理器
            gameHandlers.put(roomId, handler);
            
            System.out.println("长沙麻将AI机器人成功连接到游戏服务器: " + host + ":" + port + 
                             "，房间: " + roomId + "，玩家: " + playerId);
            
            return true;
        } catch (Exception e) {
            System.err.println("连接到游戏服务器时发生错误: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 发送协议到指定房间的游戏服务器
     */
    public boolean sendProtocolToRoom(String roomId, String command, ITObject params) {
        CSMJHandler handler = gameHandlers.get(roomId);
        if (handler != null && handler.isConnected()) {
            handler.sendToGameServer(command, params, response -> {
                System.out.println("协议 " + command + " 发送响应: " + response.returnCode);
            });
            return true;
        } else {
            System.err.println("房间 " + roomId + " 的处理器不存在或未连接");
            return false;
        }
    }
    
    /**
     * 获取房间的处理器
     */
    public CSMJHandler getHandlerForRoom(String roomId) {
        return gameHandlers.get(roomId);
    }
    
    /**
     * 断开指定房间的连接
     */
    public void disconnectRoom(String roomId) {
        CSMJHandler handler = gameHandlers.remove(roomId);
        if (handler != null) {
            handler.disconnect();
            System.out.println("已断开房间 " + roomId + " 的连接");
        }
    }
    
    /**
     * 断开所有连接
     */
    public void disconnectAll() {
        for (Map.Entry<String, CSMJHandler> entry : gameHandlers.entrySet()) {
            entry.getValue().disconnect();
        }
        gameHandlers.clear();
        System.out.println("已断开所有连接");
    }
    
    /**
     * 检查房间连接状态
     */
    public boolean isRoomConnected(String roomId) {
        CSMJHandler handler = gameHandlers.get(roomId);
        return handler != null && handler.isConnected();
    }
    
    /**
     * 注册到Redis服务
     */
    public void registerToRedis() {
        try {
            Jedis jedis = Redis.use("group1_db11").getJedis();
            try {
                // 注册服务信息
                String serviceKey = "robot_service:mj_cs";
                jedis.hset(serviceKey, "host", "127.0.0.1"); // 当前主机地址
                jedis.hset(serviceKey, "port", "7701");      // 当前服务端口
                jedis.hset(serviceKey, "status", "online");  // 服务状态
                jedis.hset(serviceKey, "wanfa_id", "10");    // 长沙麻将玩法ID
                jedis.hset(serviceKey, "connected_rooms", String.valueOf(gameHandlers.size()));
                
                System.out.println("长沙麻将机器人服务已注册到Redis");
            } finally {
                jedis.close();
            }
        } catch (Exception e) {
            System.err.println("注册到Redis失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 更新服务状态
     */
    public void updateServiceStatus() {
        try {
            Jedis jedis = Redis.use("group1_db11").getJedis();
            try {
                String serviceKey = "robot_service:mj_cs";
                jedis.hset(serviceKey, "connected_rooms", String.valueOf(gameHandlers.size()));
                jedis.hset(serviceKey, "last_update", String.valueOf(System.currentTimeMillis()));
            } finally {
                jedis.close();
            }
        } catch (Exception e) {
            System.err.println("更新服务状态失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}