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

/**
 * 菜刀效果：
 * 每次攻击造成额外伤害，伤害为斐波那契数列
 * 从1开始
 */


function fibonacci(n: number): number {
    if (n < 0) return 0;
    if (n === 0) return 0;
    if (n === 1) return 1;

    let a = 0;
    let b = 1;
    let result = 0;

    for (let i = 2; i <= n; i++) {
        result = a + b;
        a = b;
        b = result;
    }

    return result;
}

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



world.afterEvents.entityHurt.subscribe((event) => {
    if (event.damageSource.damagingEntity?.typeId !== 'minecraft:player') return;
    // 获取攻击者
    const attacker = event.damageSource.damagingEntity as Player;
    // 获取受害者
    const victim = event.hurtEntity;
    // 获取攻击者的手持武器是否有xxr:caidao
    const item = attacker.getComponent(EntityComponentTypes.Equippable)?.getEquipment(EquipmentSlot.Mainhand);
    if (item?.hasComponent('xxr:creeper_sword')) {
        // 有xxr:caidao组件，执行逻辑
        const hitCount = victim.getDynamicProperty(`${attacker.id}_${item.typeId}_xxr:caidao`) as number || 0;
        const newHitCount = hitCount + 1;
        victim.setDynamicProperty(`${attacker.id}_${item.typeId}_xxr:caidao`, newHitCount);
        try {
            const fibDamage = fibonacci(newHitCount);
            // 造成伤害
            applyDamage(victim, fibDamage);
            // 播放菜刀音效
            attacker.playSound('xxr.caidao');

        } catch (error) {
            console.error('菜刀斐波那契数列伤害失败:', error);
        }
    }
})

world.afterEvents.entityDie.subscribe((event) => {
    try {
        const deadEntity = event.deadEntity;
        // 查找包含xxr:caidao的动态属性
        const dynamicPropertyIds = deadEntity.getDynamicPropertyIds().filter((id) =>
            id.includes('_xxr:caidao')
        );
        // 重置所有包含xxr:caidao的动态属性
        dynamicPropertyIds.forEach((id) => deadEntity.setDynamicProperty(id, 0));
    } catch (error) {
        console.error('重置菜刀动态属性失败:', error);
    }
})

