package net.mcreator.phayriosisreborn.meteor;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 * One-shot lifecycle gate for the automatic infection meteor.
 *
 * The heavy/tick-driven scheduler and launch workers are completely unregistered
 * after the first successful meteor launch. This avoids leaving a permanent
 * per-tick rejection check running for the rest of the world's lifetime.
 *
 * successfulLaunches in PhayriosisMeteorEventData is the persistent per-world
 * kill switch. On a later load, EventData.load invokes onStateLoaded once and
 * retires the workers immediately for a world that has already consumed its meteor.
 *
 * A tiny server-start listener remains so a different world opened in the same
 * Minecraft JVM can re-arm the workers without requiring a client restart.
 */
@Mod.EventBusSubscriber(modid = "phayriosisreborn", bus = Mod.EventBusSubscriber.Bus.FORGE)
public final class PhayriosisMeteorOneShotGate {
    private static boolean workersRegistered = true;

    private PhayriosisMeteorOneShotGate() {}

    public static void onStateLoaded(PhayriosisMeteorEventData state) {
        if (state == null || state.successfulLaunches < 1.0D) return;

        // Make the current event-dispatch snapshot harmless. EventBus unregistration
        // may happen while a LevelTickEvent is already being dispatched.
        state.pendingMeteor = false;
        state.pendingSinceGameTime = -1.0D;
        state.nextCheckGameTime = Double.MAX_VALUE;
        state.nextLaunchAttemptGameTime = Double.MAX_VALUE;
        retireTickWorkers();
    }

    public static void retireTickWorkers() {
        if (!workersRegistered) return;
        MinecraftForge.EVENT_BUS.unregister(PhayriosisMeteorScheduler.class);
        MinecraftForge.EVENT_BUS.unregister(PhayriosisMeteorLaunchSystem.class);
        workersRegistered = false;
        System.out.println("[Phayriosis Meteor] one-shot event consumed; meteor tick workers retired for this server");
    }

    @SubscribeEvent
    public static void onServerAboutToStart(ServerAboutToStartEvent event) {
        if (workersRegistered) return;
        MinecraftForge.EVENT_BUS.register(PhayriosisMeteorScheduler.class);
        MinecraftForge.EVENT_BUS.register(PhayriosisMeteorLaunchSystem.class);
        workersRegistered = true;
        System.out.println("[Phayriosis Meteor] meteor tick workers armed for server start");
    }
}
