import * as mc from "@minecraft/server";
import { itemManager } from "../sgs_cake_lib";
const WATERING_RADIUS = 1;

export const INTERACT_ENTITIES = [
    {
        id: "minecraft:cow",
        return_id: "sgs_cake:milk_bottle"
    }
]

mc.world.beforeEvents.playerInteractWithEntity.subscribe((data) => {
    const entity = data.target;
    const player = data.player;

    const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
    const heldItem = mainhand.getItem();
    if (heldItem == undefined) return;

    if (heldItem.typeId == "sgs_cake:bottle") {

        const entityData = INTERACT_ENTITIES.find((f) => f.id == entity.typeId);
        if (entityData == undefined) return;

        mc.system.runTimeout(() => {

            player.dimension.playSound("bottle.fill", player.location);
            if (player.getGameMode() != mc.GameMode.Creative) mainhand.setItem(itemManager.reduceAmount(heldItem, 1));

            const dropItem = new mc.ItemStack(entityData.return_id, 1);
            const itemEntity = player.dimension.spawnItem(dropItem, player.location);
            itemEntity.clearVelocity();
        }, 1)
        return;
    };
});


export class bottleManager {

    static onUseOn(data) {
        const player = data.source
        const block = data.block;
        const dimension = block.dimension;
        const location = block.location;
        const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
        const heldItem = mainhand.getItem();

        let waterblock;
        for (let x = -WATERING_RADIUS; x < WATERING_RADIUS + 1; x++) {
            for (let z = -WATERING_RADIUS; z < WATERING_RADIUS + 1; z++) {
                const checkBlock = dimension.getBlock({ x: location.x + x, y: location.y, z: location.z + z });
                if (waterblock == undefined && checkBlock.typeId == "minecraft:water") {
                    waterblock = checkBlock;
                    break;
                }
            }
        };

        if (waterblock != undefined) {
            block.dimension.playSound("bottle.fill", block.center());
            if (player.getGameMode() != mc.GameMode.Creative) mainhand.setItem(itemManager.reduceAmount(heldItem, 1));

            mc.system.runTimeout(() => {
                const dropItem = new mc.ItemStack("sgs_cake:water_bottle", 1);
                const itemEntity = block.dimension.spawnItem(dropItem, player.location);
                itemEntity.clearVelocity();
            }, 1)
        }
    }
}