package fr.koka99cab.sanctuary.world;

import fr.koka99cab.sanctuary.SanctuaryMod;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLevelEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.storage.LevelData;

public final class SanctuarySpawn {
	private static final ResourceKey<NoiseGeneratorSettings> SANCTUARY_NOISE_SETTINGS = ResourceKey.create(
		Registries.NOISE_SETTINGS,
		Identifier.fromNamespaceAndPath(SanctuaryMod.MOD_ID, "sanctuary")
	);
	private static final BlockPos SPAWN_POS = new BlockPos(0, 122, -20);

	private SanctuarySpawn() {
	}

	public static void register() {
		ServerLevelEvents.LOAD.register(SanctuarySpawn::setSpawnIfSanctuaryWorld);
		ServerLifecycleEvents.SERVER_STARTED.register(server -> setSpawnIfSanctuaryWorld(server, server.overworld()));
	}

	private static void setSpawnIfSanctuaryWorld(MinecraftServer server, ServerLevel world) {
		if (isSanctuaryWorld(world)) {
			server.setRespawnData(LevelData.RespawnData.of(Level.OVERWORLD, SPAWN_POS, 0.0F, 0.0F));
		}
	}

	private static boolean isSanctuaryWorld(ServerLevel world) {
		ChunkGenerator generator = world.getChunkSource().getGenerator();
		return generator instanceof NoiseBasedChunkGenerator noiseGenerator
			&& noiseGenerator.generatorSettings().is(SANCTUARY_NOISE_SETTINGS);
	}
}
