package com.yaohun.demonskills.util;

import com.yaohun.demonskills.SkillsMain;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.ArrayList;
import java.util.List;

public class AsyncPlayerDataSaver {

    private final SkillsMain plugin;
    private final int batchSize = 5;
    private final int delayBetweenBatches = 20; // 每批延迟1秒（20tick）

    public AsyncPlayerDataSaver(SkillsMain plugin) {
        this.plugin = plugin;
        startAutoSave();
    }

    public void startAutoSave() {
        new BukkitRunnable() {
            @Override
            public void run() {
                List<Player> onlinePlayers = new ArrayList<>(Bukkit.getOnlinePlayers());
                if (onlinePlayers.isEmpty()) {
                    return;
                }

                int total = onlinePlayers.size();
                int batches = (int) Math.ceil((double) total / batchSize);

                for (int i = 0; i < batches; i++) {
                    final int batchIndex = i;

                    new BukkitRunnable() {
                        @Override
                        public void run() {
                            int start = batchIndex * batchSize;
                            int end = Math.min(start + batchSize, total);

                            for (int j = start; j < end; j++) {
                                Player p = onlinePlayers.get(j);
                                Bukkit.getScheduler().runTaskAsynchronously(SkillsMain.inst(), () -> {
                                    savePlayerData(p); // 你的保存方法（异步安全）
                                });
                            }
                        }
                    }.runTaskLater(SkillsMain.inst(), (long) delayBetweenBatches * i);
                }
            }
        }.runTaskTimer(SkillsMain.inst(), 20 * 60 * 10, 20 * 60 * 10); // 每5分钟执行一次
    }

    private void savePlayerData(Player player) {
        // TODO: 将你的数据写入YAML或数据库
        // 注意线程安全，例如避免直接操作 Bukkit API，只处理内存数据快照
    }
}

