import { world, system, ItemStack, Player } from "@minecraft/server";
import * as defaultWorldArrays from "../arrays/default_world_arrays.js"
import * as ballistaArrays from "../arrays/ballista_arrays.js"
import * as ballistaData from "../data/ballista_data.js"
import * as ballistaUtilities from "../utilities/ballista_utilities.js"
import * as mathUtilities from "../utilities/math_utilities.js"

system.runInterval(() => {
	for (const dim of defaultWorldArrays.addonDimensions) {
		const entities = world.getDimension(dim).getEntities(ballistaArrays.ballistaFamilyTypes);
		for (const ballista of entities) {
			ballistaUtilities.ballistaMainComponents(ballista);
		}
	}
},0);
world.afterEvents.playerInteractWithEntity.subscribe(({itemStack,player,target:ballista}) => {
	const ballistaOnList = ballistaArrays.ballistaIdentifierTypes.includes(ballista.typeId);
	const rule = ballistaData.ballistaDataTypes[ballista.typeId];
	if (!ballistaOnList||!rule) return;
	const xRot = ballista.getProperty(rule.properties.x_rot);
	const hasBolt = ballista.getProperty(rule.properties.has_bolt);
	const state = ballista.getProperty(rule.properties.state.identifier);
	if (!itemStack&&player.isSneaking&&state==rule.properties.state.values[4]) {
		system.runTimeout(() => {
			const yaw = ballista.getRotation().y;
			const dir = ballistaUtilities.getBallistaDirectionFromRotation(yaw,xRot);
			ballistaUtilities.ballistaLooseBoltProjectile(ballista,rule,dir,player);
		},0);
	};
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(({entity:ballistaBolt,eventId}) => {
	const ballistaBoltOnList = ballistaArrays.ballistaBoltIdentifierTypes.includes(ballistaBolt.typeId);
	const rule = ballistaData.ballistaBoltDataTypes[ballistaBolt.typeId];
	if (!ballistaBoltOnList||!rule) return;
	if (eventId==rule.events.drop_item) {
		if (rule.item_dropped) ballistaBolt.dimension.spawnItem(new ItemStack(rule.item_dropped,1),ballistaBolt.location);
		else ballistaBolt.dimension.spawnItem(new ItemStack(ballistaBolt.typeId,1),ballistaBolt.location);
		ballistaBolt.triggerEvent(rule.events.remove_entity);
	}
	if (eventId==rule.events.remove_entity) {
		ballistaBolt.remove();
	}
});