import { world, EntityComponentTypes, ItemStack, EquipmentSlot, Player } from '@minecraft/server'

world.afterEvents.playerInteractWithEntity.subscribe(event => {
    const { target, player, itemStack } = event

    captureChicken(target, player, itemStack)
})

export function captureChicken(chicken, player, itemStack) {
    if (!itemStack) return
    if (itemStack.typeId != 'ds_mc:capture_net') return

    let familyComponent = chicken.getComponent(EntityComponentTypes.TypeFamily)
    if (!familyComponent) return

    if (chicken.getComponent(EntityComponentTypes.TypeFamily).hasTypeFamily('ds_chicken')) {
        if (chicken.getProperty('ds_mc:allow_capture')) {
            let equipmentComponent = player.getComponent(EntityComponentTypes.Equippable)

            if (equipmentComponent) {
                let item = new ItemStack(`${chicken.typeId}_captured`, 1)
                equipmentComponent.setEquipment(EquipmentSlot.Mainhand, item)
            }

            chicken.remove()
        }
    }

}

//captured chicken
world.afterEvents.itemUseOn.subscribe(event => {
    let { itemStack, source } = event

    if (itemStack.typeId.startsWith('ds_mc:') && itemStack.typeId.endsWith('_captured')) {
        if (source instanceof Player) {
            let equipmentComponent = source.getComponent(EntityComponentTypes.Equippable)

            if (equipmentComponent) {
                let item = new ItemStack('ds_mc:capture_net', 1)
                equipmentComponent.setEquipment(EquipmentSlot.Mainhand, item)
            }
        }
    }
})