import { system, world } from "@minecraft/server";
system.afterEvents.scriptEventReceive.subscribe(e => {
	const entity = e.sourceEntity;
	if (e.id == "sf_nba:hamster_in_wheel_launch") {
		if (entity.typeId != "sf_nba:hamster") {
			world.sendMessage("Error: sf_nba:hamster_in_wheel_launch can only be called from a hamster or rat.");
			return;
		}
		let hamster_wheel = entity.dimension.getEntities({
			location: entity.location,
			families: ["sf_nba:hamster_wheel"],
			minDistance: 0,
			maxDistance: 0.5,
			closest: 1
		});
		if (hamster_wheel.length == 0) return;
		let rot = hamster_wheel[0].getRotation().y;
		let dir = Math.round(((rot + 180) / 360) * 4) % 4;
		entity.runCommand("ride @s stop_riding");
		if (dir == 0) entity.applyImpulse({x: 0.0, y: 0.3, z: 2.0});
		else if (dir == 1) entity.applyImpulse({x: -2.0, y: 0.3, z: 0.0});
		else if (dir == 2) entity.applyImpulse({x: 0.0, y: 0.3, z: -2.0});
		else if (dir == 3) entity.applyImpulse({x: 2.0, y: 0.3, z: 0.0});
	}
})
const hamsterItems = [
    "black_and_white",
    "black",
    "brown",
    "gray_and_white",
    "orange",
    "peach_and_cream",
    "white"
];
world.beforeEvents.itemUseOn.subscribe(e => {
    const player = e.source;
    const hamsterItem = e.itemStack.typeId;
    const blockLocation = e.block.location;
    const blockFace = e.blockFace;
    const dimension = e.source.dimension;
    const spawnLocation = { x: blockLocation.x + 0.5, y: blockLocation.y + 0.5, z: blockLocation.z + 0.5 };
    switch (blockFace) {
        case 'Up':
            spawnLocation.y += 0.5;
            break;
        case 'Down':
            spawnLocation.y -= 0.5;
            break;
        case 'North':
            spawnLocation.z -= 0.5;
            break;
        case 'South':
            spawnLocation.z += 0.5;
            break;
        case 'West':
            spawnLocation.x -= 0.5;
            break;
        case 'East':
            spawnLocation.x += 0.5;
            break;
    }
    const item = hamsterItems.find(item => hamsterItem === (`sf_nba:${item}_hamster`));
    if (item) {
        e.cancel = true;
        const variant = item.replace('_and', '');
        system.run(() => {
            const entity = dimension.spawnEntity("sf_nba:hamster", spawnLocation);
            entity.triggerEvent(`sf_nba:spawn_random_${variant}`);
            entity.triggerEvent('sf_nba:tame');
            const tameable = entity.getComponent("tameable");
            tameable.tame(player);
        });
    }
});