import { Block, EnchantmentType, EnchantmentTypes, EquipmentSlot, GameMode, ItemStack, Player, system, world } from "@minecraft/server";
import { randomChance, testing } from "../../utils/systemHelper";
import { EntityComponents as EComponents } from "../../entities/utils/entityComponents";
import { ItemComponents as IComponents } from "../utils/itemComponents";
import { CustomBlockTags } from "../../blocks/utils/blockTags";
import { CustomItemTags } from "../utils/itemTags";
import { SoundsIds } from "../../utils/typingConstants";
import { ItemEnchantments, ItemTypeIds } from "../utils/itemConstants";
import { ItemHelper } from "../utils/itemHelper";

export const CUSTOM_DURABILITY = {
    /**
     * 
     * @param {Player} player 
     * @param {EquipmentSlot} equipmentSlot
     * @param {boolean} byPassChance 
     * @returns 
     */
    damageItem: function(player, equipmentSlot = EquipmentSlot.Mainhand, byPassChance = false) {
        system.run(() => {
            if (player.getGameMode() == GameMode.creative) return
            
            const equippable = EComponents.getEquippable(player)
            const itemStack = equippable.getEquipment(equipmentSlot)
            const itemDurability = IComponents.getDurability(itemStack);
            const itemEnchantment = IComponents.getEnchantable(itemStack);
            const unbreakingLevel = itemEnchantment?.getEnchantment(ItemEnchantments.unbreaking)?.level ?? 0;
            const damageChance = itemDurability?.getDamageChance(unbreakingLevel)
    
            if (!itemDurability) return // testing.error("Item has no durability component")
            if (!byPassChance && !randomChance(damageChance / 100)) return
    
            try {
                itemDurability.damage += 1
            } catch {}
    
            if (itemDurability.damage >= itemDurability.maxDurability) {
                equippable.setEquipment(equipmentSlot, new ItemStack(ItemTypeIds.air))
                world.playSound(SoundsIds.randomBreak, player.location);
            } else {
                equippable.setEquipment(equipmentSlot, itemStack)
            }

        })
    },

    /**
     * 
     * @param {GameMode} playerGamemode 
     * @param {Block} brokenBlock 
     * @param {ItemStack} itemStack
     * @returns 
     */
    shouldDamageItem: function(playerGamemode, brokenBlock, itemStack) {
        if (playerGamemode == GameMode.creative) return;
    
        if (!ItemHelper.getItemToolTier(itemStack)) return;
        if (CustomBlockTags.willNotCostDurability(brokenBlock)) return;

        // testing.success("Item should be damaged")
        return true
    }
    
}