// @ts-check
import { world, system } from "@minecraft/server";
import { isRedMoon } from "../moon/moon_handler";

world.beforeEvents.worldInitialize.subscribe((event) => {
	event.blockComponentRegistry.registerCustomComponent(
		"hb_hr:fog_dweller_gravestone",
		{
			// Ticks on average every 10 seconds
			onTick: (block) => {
				// SNOW LAYER
				try {
					const blockAbove = block.block.above();
					if (blockAbove?.typeId === "minecraft:snow_layer") {
						blockAbove.setType("minecraft:air");
					}
				} catch {
					// Not really important
				}

				// SPAWNING DWELLERS
				// Random check: It's set to 16% chance per onTick event (10 seconds)
				// 1-(1-0.16)^4 = 0.50212864
				// The above means that it's roughly 50% chance in 4 rolls (40 seconds)
				const randomThreshold = isRedMoon() ? 1 : 0.16;
				if (Math.random() > randomThreshold) {
					return;
				}

				// Check if the doMobSpawning is enabled
				if (!world.gameRules.doMobSpawning) {
					return;
				}
				// Check if it's a night
				if (world.getTimeOfDay() < 13000) {
					// Must be after 'time set night' time
					return;
				}
				const { location, dimension } = block.block;
				// Find if there are players around
				const players = dimension.getPlayers({
					location,
					maxDistance: 40,
				});
				if (players.length === 0) {
					return;
				}
				// Check if there are any other fog dwellers around
				const fogDwellers = dimension.getEntities({
					type: "hb_hr:fog_dweller",
					location,
					maxDistance: 200,
				});
				if (fogDwellers.length > 0) {
					return;
				}

				// Summon a lightning bolt at the location of the gravestone
				dimension.spawnEntity("minecraft:lightning_bolt", location);
				// Remove the gravestone and spawn the fog dweller. There is a small
				// delay to avoid hurting the fog dweller with the lightning bolt
				system.runTimeout(() => {
					// Because of the delay we have to validate the location and the type
					// of the block again
					try {
						const block = dimension.getBlock(location);
						if (
							block === undefined ||
							block.typeId !== "hb_hr:fog_dweller_gravestone"
						) {
							return;
						}
						const { x, y, z } = location;
						dimension.runCommand(`setblock ${x} ${y} ${z} chest[] destroy`);
						dimension.runCommand(
							`loot insert ${x} ${y} ${z} loot "hb/hr/blocks/fog_dweller_chest"`
						);
					} catch {
						return;
					}
					dimension.spawnEntity("hb_hr:fog_dweller", location);
				}, 20);
			},
		}
	);
});
