import { Player, createPlayer } from '../models/Player';
import { worldManager } from './WorldManager';

/**
 * 玩家管理器
 * 负责玩家数据的存储、查询和管理
 */
class PlayerManager {
    /** 玩家数据存储 (key: playerId) */
    private players: Map<string, Player> = new Map();
    
    /** 在线玩家连接 (key: playerId, value: connectionId) */
    private onlinePlayers: Map<string, string> = new Map();

    /**
     * 根据玩家ID查找玩家
     */
    getPlayer(playerId: string): Player | undefined {
        return this.players.get(playerId);
    }

    /**
     * 检查玩家是否存在
     */
    hasPlayer(playerId: string): boolean {
        return this.players.has(playerId);
    }

    /**
     * 创建新玩家
     */
    createPlayer(playerId: string, playerName?: string): Player {
        if (this.players.has(playerId)) {
            throw new Error(`玩家 ${playerId} 已存在`);
        }

        // 生成出生点
        const spawnPoint = worldManager.generateSpawnPosition();
        
        // 创建玩家
        const name = playerName || `玩家${playerId.substring(0, 6)}`;
        const player = createPlayer(playerId, name, spawnPoint);
        
        // 保存玩家数据
        this.players.set(playerId, player);
        
        console.log(`创建新玩家: ${player.name} (${playerId})`);
        console.log(`  出生点: (${spawnPoint.x}, ${spawnPoint.y})`);
        
        return player;
    }

    /**
     * 获取或创建玩家（登录流程）
     */
    getOrCreatePlayer(playerId: string, playerName?: string): Player {
        let player = this.players.get(playerId);
        
        if (player) {
            // 玩家已存在，更新最后登录时间
            player.lastLoginAt = Date.now();
            console.log(`玩家登录: ${player.name} (${playerId})`);
        } else {
            // 新玩家，创建角色
            player = this.createPlayer(playerId, playerName);
        }
        
        return player;
    }

    /**
     * 设置玩家在线状态
     */
    setPlayerOnline(playerId: string, connectionId: string): void {
        this.onlinePlayers.set(playerId, connectionId);
    }

    /**
     * 设置玩家离线
     */
    setPlayerOffline(playerId: string): void {
        this.onlinePlayers.delete(playerId);
        console.log(`玩家离线: ${playerId}`);
    }

    /**
     * 检查玩家是否在线
     */
    isPlayerOnline(playerId: string): boolean {
        return this.onlinePlayers.has(playerId);
    }

    /**
     * 获取玩家连接ID
     */
    getPlayerConnectionId(playerId: string): string | undefined {
        return this.onlinePlayers.get(playerId);
    }

    /**
     * 更新玩家位置
     */
    updatePlayerPosition(playerId: string, x: number, y: number): boolean {
        const player = this.players.get(playerId);
        if (!player || !player.isAlive) {
            return false;
        }

        // 验证位置是否合法
        if (!worldManager.isValidPosition({ x, y })) {
            return false;
        }

        player.position.x = x;
        player.position.y = y;
        return true;
    }

    /**
     * 获取所有在线玩家
     */
    getOnlinePlayers(): Player[] {
        const players: Player[] = [];
        for (const playerId of this.onlinePlayers.keys()) {
            const player = this.players.get(playerId);
            if (player) {
                players.push(player);
            }
        }
        return players;
    }

    /**
     * 获取玩家总数
     */
    getTotalPlayers(): number {
        return this.players.size;
    }

    /**
     * 获取在线玩家数
     */
    getOnlinePlayerCount(): number {
        return this.onlinePlayers.size;
    }
}

// 导出单例
export const playerManager = new PlayerManager();
