import { getOrientation } from "../../functions";

const shovelDestroyList = [
    "grass",
    "dirt"
];

export default {
    async execute(item, player, destroyedBlock) {
        const tag = item?.getTags()?.find(tag => tag == "break:hoe");

        if (!tag || !destroyedBlock) return;
        const { x: bX, y: bY, z: bZ } = destroyedBlock.location;
        const playerOrientationY = getOrientation(player.getRotation().y);
        const playerOrientationX = getOrientationX(player.getRotation().x);

        for (let deltaY = -1; deltaY <= 1; deltaY += 1) {
            for (let deltaXZ = -1; deltaXZ <= 1; deltaXZ += 1) {
                if (deltaXZ === 0 && deltaY === 0) continue; // Saltar la coordenada del bloque 'c'
                let x, y, z;

                if (playerOrientationX >= 0) {
                    x = bX < 0 ? bX - deltaY : bX + deltaY;
                    y = bY;
                    z = bZ < 0 ? bZ - deltaXZ : bZ + deltaXZ;
                }
                const block = player.dimension.getBlock({ x, y, z });
                
                if (!block || !shovelDestroyList.find(tag => block.hasTag(tag))) continue;
                block.setType("minecraft:farmland");
            }
        }
    }
}

function getOrientationX(playerRotationX) {
    switch (true) {
        case playerRotationX > 27:
            return 1;
        case playerRotationX < -19:
            return 0;
        default:
            return 1;
    }
}