package me.km;

import me.km.networking.ModPacketHandler;
import me.km.world.ModWorldGeneration;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DeferredWorkQueue;
import net.minecraftforge.fml.event.server.FMLServerStoppedEvent;

@Mod.EventBusSubscriber
@Mod("km")
public class KajetansMod {
    public static final String MODID = "km";

    public KajetansMod() {
        ClassLoaderUtils.loadDependencies();

        IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
        bus.addListener(this::init);
        bus.addListener(this::setupServer);
        bus.addListener(this::clientInit);
        bus.addListener(this::onServerStop);

        MinecraftForge.EVENT_BUS.register(this);
    }

    private void init(FMLCommonSetupEvent e) {
        DeferredWorkQueue.runLater(() -> ModPacketHandler.init());
        ModWorldGeneration.register();

        MinecraftForge.EVENT_BUS.register(new CommonEvents());
    }

    private void clientInit(FMLClientSetupEvent e) {
        Client.init();
    }

    private void setupServer(FMLDedicatedServerSetupEvent e) {
        Server.onStart(e.getServerSupplier().get());
    }

    @SubscribeEvent
    public void onServerStop(FMLServerStoppedEvent e) {
        if(e.getServer().isDedicatedServer()) {
            Server.onStop();
        }
    }
}
