import { EntityComponentTypes, EntityDamageCause, EquipmentSlot, Player, system, world } from "@minecraft/server";
import { applyDamage } from "../../types/function";

/**
 * 玻璃剑效果：
 * 20%的概率伤害x2
 */

system.beforeEvents.startup.subscribe((init) => {
    init.itemComponentRegistry.registerCustomComponent('xxr:glass_sword', {
        onHitEntity: (event) => {
            // 注册占位
        }
    })
})

world.afterEvents.entityHurt.subscribe((event) => {
    if (event.damageSource.damagingEntity?.typeId !== 'minecraft:player') return;
    // 获取攻击者
    const attacker = event.damageSource.damagingEntity as Player;
    // 获取攻击者的手持武器是否有xxr:glass_sword组件
    const item = attacker.getComponent(EntityComponentTypes.Equippable)?.getEquipment(EquipmentSlot.Mainhand);
    if (item?.hasComponent('xxr:glass_sword')) {
        // 有xxr:glass_sword组件，执行逻辑
        const damage = event.damage;
        if (Math.random() < 0.2) {
            try {
                // 造成伤害x2
                applyDamage(event.hurtEntity, damage * 2);
                // 播放玻璃破碎音效
                attacker.playSound('random.glass');
            } catch (error) {
                console.error('玻璃剑伤害x2失败:', error);
            }
        }
    }
})


