import { system, world, EntityComponentTypes } from '@minecraft/server'
import { snapRotation, getDistance } from 'ds/mch/entity/entity.js'
import { getAllEntities } from 'ds/mch/world/world.js'
import { showBorders, hideBorders } from 'ds/mch/entity/chicken_nest.js'

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

    if (entity.typeId === 'ds_mc:egg_collector') {
        snapRotation(entity),
            entity.nameTag = 'Egg Collector'
    }
})

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

    if (removedEntity.typeId === 'ds_mc:egg_collector') {
        const dimension = removedEntity.dimension
        const location = removedEntity.location

        system.runTimeout(() => {
            dimension.runCommand(`loot spawn ${location.x} ${location.y} ${location.z} loot "ds/mch/egg_collector"`)
        }, 1)

        //drop inventory
        const inventory = removedEntity.getComponent(EntityComponentTypes.Inventory)
        if (inventory) {
            if (inventory.container) {
                const container = inventory.container
                const size = container.size

                for (let i = 0; i < size; i++) {
                    const item = container.getItem(i)
                    if (item) {
                        system.runTimeout(() => {
                            dimension.spawnItem(item, location)
                        }, 1)
                    }
                }
            }
        }
    }
})

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

    if (target.typeId === 'ds_mc:egg_collector') {
        if (player.isSneaking) {
            toggleLinking(player, target)
            system.run(() => {
                target.playAnimation('animation.ds_mc.chicken_breeder.button')
            })

            //prevent opening inventory
            event.cancel = true
        }
    }
})

system.runInterval(() => {
    getAllEntities('ds_mc:egg_collector').forEach(collector => {
        const nestIds = collector.getDynamicPropertyIds()

        for (let nestId of nestIds) {
            const nest = world.getEntity(nestId)
            if (!nest) {
                collector.setDynamicProperty(nestId)
            } else {
                nest.dimension.getEntities(
                    {
                        type: 'minecraft:item',
                        location: nest.location,
                        maxDistance: 1
                    }
                ).forEach(item => {
                    const itemComponent = item.getComponent(EntityComponentTypes.Item)
                    if (itemComponent) {
                        if (itemComponent.itemStack.typeId.startsWith('ds_mc:') && itemComponent.itemStack.typeId.endsWith('_egg')) {
                            item.teleport(collector.location)
                        }
                    }
                })
            }
        }
    })
}, 20)

function toggleLinking(player, entity) {
    if (player.getDynamicProperty('linking_nest')) {
        player.setDynamicProperty('linking_nest')
        hideBorders()
        player.sendMessage('You stopped linking')
    } else {
        player.setDynamicProperty('linking_nest', entity.id)
        showBorders()
        player.sendMessage('You can now start linking')
    }
}

export function linkNest(player, nest) {
    let collectorId = player.getDynamicProperty('linking_nest')

    if (collectorId) {
        let collector = world.getEntity(collectorId)
        const distance = getDistance(collector, nest)

        if (distance > 10) {
            player.sendMessage('§cThis nest is too far away')
            return
        }

        if (collector.getDynamicProperty(nest.id)) {
            collector.setDynamicProperty(nest.id)
            nest.setProperty('ds_mc:is_linked', false)
            player.sendMessage('Nest unlinked')
        } else {
            if (collector.getDynamicPropertyIds().length >= 4) {
                player.sendMessage('§cThis collector has reached the maximum linked nests')
                return
            }

            collector.setDynamicProperty(nest.id, true)
            nest.setProperty('ds_mc:is_linked', true)
            player.sendMessage('Nest linked')
        }
    }
}