import { world, system, ItemStack, TicksPerSecond, BlockPermutation, Block, Player, MolangVariableMap, ItemTypes, Entity } from '@minecraft/server';


export function itemDurability(player, itemStack, damage) {
    if (damage === undefined) { damage = 1 }
    if (itemStack.hasComponent('minecraft:durability') !== false) {
        var damageChance = 100
        if (itemStack.getComponent('minecraft:enchantable') !== undefined) {
            if (itemStack.getComponent('minecraft:enchantable').hasEnchantment("unbreaking")) {
                damageChance = itemStack.getComponent('minecraft:durability').getDamageChance(itemStack.getComponent('minecraft:enchantable').getEnchantment("unbreaking").level)
            }
        }
        if (Math.random() < (damageChance / 100)) {
            var itemDurability = itemStack.getComponent('minecraft:durability')
            if (itemDurability.damage + damage < itemDurability.maxDurability) {
                itemDurability.damage++
                player.getComponent('minecraft:inventory').container.getSlot(player.selectedSlotIndex).setItem(itemStack)
            }
            else {
                player.getComponent('minecraft:inventory').container.getSlot(player.selectedSlotIndex).setItem()
                player.playSound('random.break')
            }
        }
    }
    else {
        if (itemStack.amount - damage > 0) {
            itemStack.amount--
            player.getComponent('minecraft:inventory').container.getSlot(player.selectedSlotIndex).setItem(itemStack)
        }
        else if (itemStack.amount - damage < 0) {
            return
        }
        else {
            player.getComponent('minecraft:inventory').container.getSlot(player.selectedSlotIndex).setItem()
        }
    }
}

export function itemAttack(player) {
    if (player.typeId == "minecraft:player") {
        var itemStack = player.getComponent('minecraft:inventory').container.getItem(player.selectedSlotIndex)
        if (itemStack === undefined) return
        {
            itemDurability(player, itemStack)
        }
    }


}

export function itemMine(player) {
    if (player.typeId == "minecraft:player") {
        var itemStack = player.getComponent('minecraft:inventory').container.getItem(player.selectedSlotIndex)
        if (itemStack === undefined) return
        {
            itemDurability(player, itemStack)
        }
    }


}