package com.yaohun.storyline.manage;

import com.yaohun.storyline.config.Config;
import com.yaohun.storyline.core.Quest;
import com.yaohun.storyline.data.PlayerData;
import me.Demon.DemonLevels.api.DLevelAPI;
import me.Demon.DemonPlugin.DemonAPI;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PlayerManager {

    private HashMap<String, PlayerData> playerDataMap = new HashMap<>();

    public List<PlayerData> getAllPlayerData() {
        return new ArrayList<>(playerDataMap.values());
    }

    public void createPlayerData(Player player) {
        String playerName = player.getName();
        if(!playerDataMap.containsKey(playerName)) {
            File file = new File(Config.getDataPath(), playerName + ".yml");
            if(!file.exists()){
                PlayerData playerData = new PlayerData(playerName);
                playerDataMap.put(playerName, playerData);
                playerData.receiveQuest(QuestManager.getQuest(1));
                Bukkit.getConsoleSender().sendMessage("§c[主线任务] §a玩家 §e"+playerName+" §a已开启新手引导任务.");
            } else {
                Bukkit.getConsoleSender().sendMessage("§c[主线任务] §a玩家 §e"+playerName+" §a已创建过引导档案.");
            }
        } else {
            Bukkit.getConsoleSender().sendMessage("§c[主线任务] §a玩家 §e"+playerName+" §a已正在进行引导任务.");
        }
    }

    public void stopPlayerData(Player player) {
        String playerName = player.getName();
        if(playerDataMap.containsKey(playerName)) {
            PlayerData playerData = playerDataMap.get(playerName);
            playerData.stopPlayerData();
        } else {
            Bukkit.getConsoleSender().sendMessage("§c[主线任务] §a玩家 §e"+playerName+" §a貌似并没有进行主题任务.");
        }
    }

    public PlayerData getPlayerData(String playerName) {
        if(!playerDataMap.containsKey(playerName)) {
            File file = new File(Config.getDataPath(), playerName + ".yml");
            if(!file.exists()){
                return null;
            }
            FileConfiguration config = YamlConfiguration.loadConfiguration(file);
            int currentQuest = config.getInt("currentQuest",1);
            ConfigurationSection section = config.getConfigurationSection("quests");
            HashMap<Quest, Integer> questAmountMap = new HashMap<>();
            if(section != null) {
                for (String key : section.getKeys(false)) {
                    try {
                        int questID = Integer.parseInt(key);
                        Quest quest = QuestManager.getQuest(questID);
                        if(quest != null) {
                            int amount = section.getInt(key);
                            questAmountMap.put(quest, amount);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
            PlayerData playerData = new PlayerData(playerName, currentQuest,questAmountMap);
            playerDataMap.put(playerName, playerData);
            return playerData;
        }
        return playerDataMap.get(playerName);
    }

    public void savePlayerData(PlayerData data) {
        File file = new File(Config.getDataPath(), data.getPlayerName() + ".yml");
        FileConfiguration config = new YamlConfiguration();
        config.set("SaveTime", DemonAPI.getTime("yyyy/MM/dd HH:mm:ss"));
        config.set("currentQuest",data.getCurrentQuest());
        ConfigurationSection section = config.createSection("quests");
        for (Quest quest : data.getAllQuest()){
            // System.out.println("# "+quest.getQuestID()+" "+data.getQuestAmount(quest));
            section.set(String.valueOf(quest.getQuestID()),data.getQuestAmount(quest));
        }
        try {
            config.save(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAllPlayerData() {
        File folder = new File(Config.getDataPath());
        if (!folder.exists()) {
            folder.mkdirs(); // 确保路径存在
        }
        int successCount = 0;
        int failCount = 0;
        for (PlayerData data : playerDataMap.values()) {
            try {
                savePlayerData(data); // 单人保存方法
                successCount++;
            } catch (Exception e) {
                Bukkit.getLogger().severe("[剧情任务] 保存玩家任务数据失败：" + data.getPlayerName() + " - 错误：" + e.getMessage());
                e.printStackTrace();
                failCount++;
            }
        }
        Bukkit.getLogger().info("[剧情任务] 保存玩家任务数据完成：成功 " + successCount + " 人，失败 " + failCount + " 人。");
        playerDataMap.clear();
    }
}
