package com.tiedup.remake.entities.skins;

import com.tiedup.remake.core.TiedUpMod;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.profiling.ProfilerFiller;

/**
 * Forge reload listener for entity skins.
 *
 * Integrates with Minecraft's resource reload system to:
 * 1. Load skin definitions from datapacks on server start
 * 2. Reload skins when /reload command is executed
 *
 * Registered via AddReloadListenerEvent in TiedUpMod.
 *
 */
public class SkinReloadListener implements PreparableReloadListener {

    @Override
    public CompletableFuture<Void> reload(
        PreparationBarrier barrier,
        ResourceManager resourceManager,
        ProfilerFiller preparationsProfiler,
        ProfilerFiller reloadProfiler,
        Executor backgroundExecutor,
        Executor gameExecutor
    ) {
        // Load skins in background thread (non-blocking)
        return CompletableFuture.runAsync(
            () -> {
                preparationsProfiler.startTick();
                preparationsProfiler.push("tiedup_skin_loading");

                try {
                    TiedUpMod.LOGGER.info(
                        "[SkinReloadListener] Starting skin reload..."
                    );

                    // Load skins from datapacks
                    SkinLoader.loadSkins(resourceManager);

                    // Refresh existing managers to use new data
                    refreshManagers();

                    TiedUpMod.LOGGER.info(
                        "[SkinReloadListener] Skin reload complete"
                    );
                } catch (Exception e) {
                    TiedUpMod.LOGGER.error(
                        "[SkinReloadListener] Failed to reload skins",
                        e
                    );
                }

                preparationsProfiler.pop();
                preparationsProfiler.endTick();
            },
            backgroundExecutor
        ).thenCompose(barrier::wait);
    }

    /**
     * Refresh existing skin managers to use newly loaded data.
     */
    private void refreshManagers() {
        SkinManagers.reloadAll();
    }
}
