import { system, world, EntityComponentTypes } from '@minecraft/server'
import { snapRotation } from 'ds/mch/entity/entity.js'
import { getRiders, placeChicken } from 'ds/mch/entity/chicken_breeder.js'
import { captureChicken } from 'ds/mch/item/capture_net.js'
import { linkNest } from 'ds/mch/entity/egg_collector.js'
import { getAllEntities } from 'ds/mch/world/world.js'

//spawn
world.afterEvents.entitySpawn.subscribe(event => {
    const entity = event.entity

    if (entity.typeId === 'ds_mc:chicken_nest') {
        snapRotation(entity)
    }

    if (entity.typeId.startsWith('ds_mc:') && entity.typeId.endsWith('_chicken')) {
        let ridingComponent = entity.getComponent(EntityComponentTypes.Riding)
        if (ridingComponent) {
            const entityRidingOn = ridingComponent.entityRidingOn
            if (entityRidingOn.typeId === 'ds_mc:chicken_nest') {
                entity.setProperty('ds_mc:in_nest', true)
            }
        }
    }
})

//despawn
world.beforeEvents.entityRemove.subscribe(event => {
    const entity = event.removedEntity

    if (entity.typeId === 'ds_mc:chicken_nest') {
        let riders = getRiders(entity)
        for (let rider of riders) {
            system.run(() => {
                rider.setProperty('ds_mc:in_nest', false)
            })
        }
    }
})

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

    if (target.typeId === 'ds_mc:chicken_nest') {
        if (itemStack) {
            if (itemStack.getTags().includes('ds_mc:captured_chicken')) {
                const riders = getRiders(target)

                if (riders.length === 0) {
                    const chickenId = itemStack.typeId.replace('_captured', '')

                    if (chickenId) {
                        placeChicken(player, target, chickenId)
                    }
                }
            } else if (itemStack.typeId === 'ds_mc:capture_net') {
                const chicken = getRiders(target)[0]

                if (chicken) {
                    captureChicken(chicken, player, itemStack)
                }
            } else {
                linkNest(player, target)
            }
        } else {
            linkNest(player, target)
        }
    }
})

export function showBorders() {
    getAllEntities('ds_mc:chicken_nest').forEach(entity => {
        system.run(() => {
            entity.setProperty('ds_mc:show_border', true)
        })
    })
}

export function hideBorders() {
    getAllEntities('ds_mc:chicken_nest').forEach(entity => {
        system.run(() => {
            entity.setProperty('ds_mc:show_border', false)
        })
    })
}