import { world, system, TicksPerSecond } from "@minecraft/server";
export default class Hyena {
	static ENTITY = "sf_nba:hyena";
	static ITEM = "minecraft:rotten_flesh";
	static EVENT = "sf_nba:become_ravenous";
	static TAG = "sf_nba.half_health_and_below";
	static RAVENOUS_CHANCE = 0.2;
	static CHECK_RANGE = 10;
	static hyenas = new Set();
	constructor() {
		this.initEvents();
	}
	initEvents() {
		world.afterEvents.entityLoad.subscribe(this.handleEntityLoad.bind(this));
		world.afterEvents.entitySpawn.subscribe(this.handleEntitySpawn.bind(this));
		world.beforeEvents.entityRemove.subscribe(
			this.handleEntityRemove.bind(this)
		);
		system.runTimeout(this.initializeHyenasInPlayerDimensions.bind(this), 1);
		this.initHealthCheckInterval();
	}
	initializeHyenasInPlayerDimensions() {
		const players = world.getAllPlayers();
		const checkedDimensions = new Set();
		for (const player of players) {
			const dimension = player.dimension;
			if (checkedDimensions.has(dimension.id)) continue;
			checkedDimensions.add(dimension.id);
			const hyenas = dimension.getEntities({
				type: Hyena.ENTITY,
			});
			for (const hyena of hyenas) {
				Hyena.hyenas.add(hyena);
			}
		}
	}
	initHealthCheckInterval() {
		system.runInterval(
			this.checkNearbyEntitiesHealth.bind(this),
			TicksPerSecond
		);
	}
	handleEntityLoad(eventData) {
		const entity = eventData.entity;
		if (entity.typeId === Hyena.ENTITY) {
			Hyena.hyenas.add(entity);
		}
	}
	handleEntitySpawn(eventData) {
		const entity = eventData.entity;
		if (entity.typeId === Hyena.ENTITY) {
			Hyena.hyenas.add(entity);
		}
	}
	handleEntityRemove(eventData) {
		Hyena.hyenas.delete(eventData.removedEntity);
	}
	checkNearbyEntitiesHealth() {
		const players = world.getAllPlayers();
		if (players.length === 0) return;
		for (const hyena of Hyena.hyenas) {
			if (!hyena.isValid()) {
				Hyena.hyenas.delete(hyena);
				continue;
			}
			let playerInDimension = false;
			for (const player of players) {
				if (player.dimension.id === hyena.dimension.id) {
					playerInDimension = true;
					break;
				}
			}
			if (!playerInDimension) continue;
			const dimension = hyena.dimension;
			const location = hyena.location;
			const nearbyEntities = dimension.getEntities({
				location: location,
				maxDistance: Hyena.CHECK_RANGE,
			});
			for (const entity of nearbyEntities) {
				const health = entity.getComponent("health");
				if (!health) continue;
				const { currentValue, effectiveMax } = health;
				if (currentValue / effectiveMax <= 0.5) {
					if (!entity.hasTag(Hyena.TAG)) entity.addTag(Hyena.TAG);
				} else {
					if (entity.hasTag(Hyena.TAG)) entity.removeTag(Hyena.TAG);
				}
			}
		}
	}
}
new Hyena();