import * as server from "@minecraft/server";

function distancia3D(ponto1, ponto2) {
    const deltaX = ponto2.x - ponto1.x;
    const deltaY = ponto2.y - ponto1.y;
    const deltaZ = ponto2.z - ponto1.z;

    return Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ);
}

const face = {
    "North": 1,
    "South": -1,
    "East": 1,
    "West": -1,
    "Up": 1,
    "Down": -1
}

const facZ = {
    "North": -1,
    "South": 1,
    "East": 0,
    "West": 0,
    "Up": 0,
    "Down": 0
}

const facY = {
    "North": 0,
    "South": 0,
    "East": 0,
    "West": 0,
    "Up": 1,
    "Down": -1
}

const facX = {
    "North": 0,
    "South": 0,
    "East": 1,
    "West": -1,
    "Up": 0,
    "Down": 0
}


server.world.afterEvents.itemUse.subscribe(eventData => {
    let player = eventData.source
    let block = eventData.source.getBlockFromViewDirection()
    let item = eventData.itemStack


    if (block && player.runCommand("testfor @s[hasitem={item=crabbersdelight:crab_claw,location=slot.weapon.offhand}]").successCount == 1 && distancia3D(player.location, block.block.location) >= 5 && distancia3D(player.location, block.block.location) <= 8 && player.runCommand(`execute unless block ~~~ ${item.typeId} run testfor @s`)) {
        player.runCommand(`clear @s ${item.typeId} 0 1`)
        player.runCommand(`setblock ${block.block.location.x + facX[block.face]} ${block.block.location.y + facY[block.face]} ${block.block.location.z + facZ[block.face]} ${item.typeId}`)
    }
})