package xyz.illuc.neuralgiacore.events;

import net.dries007.tfc.util.climate.Climate;
import net.dries007.tfc.world.chunkdata.ChunkData;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Mod.EventBusSubscriber
public class UpdateClimateOnChunkLoadEvent {

    //gleeked out

    // this doesnt work its ass and bad figure a better solution out later

    private static final Map<ChunkPos, ServerLevel> pendingChunks = new ConcurrentHashMap<>();

    @SubscribeEvent
    public static void onChunkLoad(ChunkEvent.@NotNull Load event) {
        if (event.isNewChunk() || event.getLevel().isClientSide()) return;

        final ServerLevel level = (ServerLevel) event.getLevel();
        final ChunkPos pos = event.getChunk().getPos();

        pendingChunks.put(pos, level);
    }

    @SubscribeEvent
    public static void onServerTick(TickEvent.ServerTickEvent event) {
        if (event.phase != TickEvent.Phase.END || pendingChunks.isEmpty()) return;

        Map<ChunkPos, ServerLevel> toProcess = new ConcurrentHashMap<>(pendingChunks);
        toProcess.keySet().forEach(pendingChunks::remove);

        toProcess.forEach((pos, level) -> {
            LevelChunk chunk = level.getChunkSource().getChunkNow(pos.x, pos.z);

            if (chunk != null) {
                try {
                    final ChunkData chunkData = ChunkData.get(chunk);
                    Climate.onChunkLoad(level, new ImposterProtoChunk(chunk, true), chunkData);
                } catch (Exception e) {
                    System.err.println("Error updating climate for chunk " + pos + ": " + e.getMessage());
                    e.printStackTrace();
                }
            }
        });
    }


}