package com.playerblocklife;

import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;

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

/**
 * PlayerJoinListener - PlayerBlockLife游戏模式下的玩家加入和重生监听器
 * 
 * <p>处理玩家加入服务器和重生时的逻辑，包括：
 * <ul>
 *   <li>根据玩家权限设置游戏模式（OP玩家为观察者模式，非OP玩家为冒险模式）</li>
 *   <li>为非OP玩家分配独特的生命方块颜色</li>
 *   <li>给非OP玩家提供对应颜色的方块作为手持物品</li>
 *   <li>根据当前游戏状态显示相应信息</li>
 *   <li>处理玩家重生时的游戏状态恢复</li>
 * </ul>
 * 
 * <p>此监听器与GameStateManager协作，确保玩家正确加入PlayerBlockLife游戏模式。</p>
 * 
 * @author xiaobai
 * @version 2.2.0-1.20.4
 * @since 1.0.0
 */
public class PlayerJoinListener implements Listener {
    private final PlayerBlockLife plugin;

    /**
     * 构造一个新的玩家加入监听器
     * 
     * @param plugin 插件主类实例
     */
    public PlayerJoinListener(PlayerBlockLife plugin) {
        this.plugin = plugin;
    }

    @EventHandler(priority = EventPriority.NORMAL)
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        UUID playerId = player.getUniqueId();

        // 根据玩家权限设置游戏模式
        if (player.isOp()) {
            // OP玩家设置为观察者模式
            player.setGameMode(GameMode.SPECTATOR);
            player.sendMessage(org.bukkit.ChatColor.YELLOW + "您是管理员，已设置为观察者模式。");
        } else {
            // 非OP玩家设置为冒险模式
            player.setGameMode(GameMode.ADVENTURE);
            
            // 分配颜色并给玩家对应颜色的方块
            plugin.getGameStateManager().assignPlayerColor(player);
        }

        // 延迟执行，确保颜色分配完成
        Bukkit.getScheduler().runTaskLater(plugin, () -> {
            // 更新玩家的计分板
            plugin.getGameStateManager().updatePlayerScoreboard(player);
            
            // 根据游戏状态显示不同信息
            GameStateManager.GameState currentState = plugin.getGameStateManager().getCurrentState();
            if (currentState == GameStateManager.GameState.WAITING) {
                player.sendMessage(org.bukkit.ChatColor.YELLOW + "游戏等待中，请等待管理员开始游戏。");
            } else if (currentState == GameStateManager.GameState.STARTED) {
                player.sendMessage(org.bukkit.ChatColor.GREEN + "游戏中，请小心保护你的生命方块！");
            } else if (currentState == GameStateManager.GameState.FINISHED) {
                player.sendMessage(org.bukkit.ChatColor.RED + "游戏已结束，请等待下一轮开始。");
            }
        }, 20L);
    }

    /**
     * 为玩家自动生成生命方块
     */
    private void generateLifeBlocksForPlayer(Player player) {
        try {
            // 获取配置
            ConfigManager config = plugin.getConfigManager();
            boolean requireOpenSky = true; // 使用默认值，因为配置已移除
            int maxAttempts = 50; // 使用默认值，因为配置已移除
            
            // 调用方块管理器生成方块
            boolean success = plugin.getBlockManager().generateLifeBlocksForPlayer(
                player, 5, 5, requireOpenSky, maxAttempts
            );
            
            if (success) {
                // 发送成功消息
                String message = plugin.getMessageManager().getMessage("console.blocks_generated", 
                    "&a[PlayerBlockLife] 已为玩家 {player} 生成 {amount} 个生命方块");
                message = message.replace("{player}", player.getName())
                                 .replace("{amount}", String.valueOf(5)); // 使用固定值5
                // 移除颜色代码用于日志
                String logMessage = message.replace("&", "");
                plugin.getLogger().info(logMessage);
                
                // 发送给玩家
                String playerMsg = plugin.getMessageManager().getMessage("game.block.placed", 
                    "&a已为你生成 {amount} 个生命方块！");
                playerMsg = playerMsg.replace("{amount}", String.valueOf(5)) // 使用固定值5
                                     .replace("&", "§");
                player.sendMessage(playerMsg);
            } else {
                // 生成失败
                String failureMsg = plugin.getMessageManager().getMessage("console.error_generating_blocks",
                    "&c[PlayerBlockLife] 为玩家 {player} 生成生命方块时失败");
                failureMsg = failureMsg.replace("{player}", player.getName());
                // 移除颜色代码用于日志
                String logFailureMsg = failureMsg.replace("&", "");
                plugin.getLogger().warning(logFailureMsg);
                
                // 根据配置处理失败
                String onFailure = "notify"; // 使用默认值，因为配置已移除
                if (onFailure.equals("notify")) {
                    String notifyMsg = plugin.getMessageManager().getMessage("game.errors.cannot_generate_blocks",
                        "&c无法生成生命方块：{reason}");
                    notifyMsg = notifyMsg.replace("{reason}", "找不到合适的位置（尝试了20次）")
                                         .replace("&", "§");
                    player.sendMessage(notifyMsg);
                    player.sendMessage("§7请手动使用 §e/setlifeblocks §7命令生成方块");
                } else if (onFailure.equals("teleport_to_spawn")) {
                    player.teleport(player.getWorld().getSpawnLocation());
                    player.sendMessage("§e已将你传送至出生点，请手动生成方块");
                }
            }
        } catch (Exception e) {
            plugin.getLogger().severe("为玩家 " + player.getName() + " 生成生命方块时发生错误: " + e.getMessage());
            e.printStackTrace();
            
            String errorMsg = plugin.getMessageManager().getMessage("console.error_generating_blocks",
                "&c[PlayerBlockLife] 为玩家 {player} 生成生命方块时出错: {error}");
            if (errorMsg != null) {
                String errorDetail = e.getMessage() != null ? e.getMessage() : "未知错误";
                errorMsg = errorMsg.replace("{player}", player.getName())
                                   .replace("{error}", errorDetail)
                                   .replace("&", "§");
                plugin.getLogger().severe(errorMsg);
            }
        }
    }

    @EventHandler
    public void onPlayerRespawn(PlayerRespawnEvent event) {
        Player player = event.getPlayer();
        UUID playerId = player.getUniqueId();

        // 根据当前游戏状态处理玩家重生
        GameStateManager.GameState currentState = plugin.getGameStateManager().getCurrentState();
        if (currentState == GameStateManager.GameState.STARTED) {
            // 如果游戏中，检查玩家是否存活
            int remainingBlocks = plugin.getGameStateManager().getRemainingBlocks(playerId);
            if (remainingBlocks <= 0) {
                // 玩家已被淘汰，设置为观察者模式
                Bukkit.getScheduler().runTaskLater(plugin, () -> {
                    if (player.isOnline()) {
                        player.setGameMode(GameMode.SPECTATOR);
                        player.sendMessage(org.bukkit.ChatColor.YELLOW + "你已被淘汰，可以观察其他玩家。");
                    }
                }, 20L);
            }
        } else {
            // 如果游戏未开始或已结束，OP玩家保持观察者模式，非OP玩家设置为冒险模式
            if (player.isOp()) {
                player.setGameMode(GameMode.SPECTATOR);
            } else {
                player.setGameMode(GameMode.ADVENTURE);
                plugin.getGameStateManager().assignPlayerColor(player);
            }
        }
    }
}