import * as mc from "@minecraft/server"
import * as racoAPI from "../raco-API"
import { hasRedstonePower } from "../hasRedstonePower";

export function enderHopperTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false;
    const items = block.dimension.getEntities({type:'minecraft:item', location:block.above().center(), maxDistance:0.7})
    for (const item of items){
        const face = {
            'up':'below',
            'down':'below',
            'north':'south',
            'south':'north',
            'west':'east',
            'east':'west'
        }
        const itemStack = item.getComponent("minecraft:item").itemStack
        const direction = block.permutation.getState('minecraft:block_face')
        const container = block[face[direction]]()?.getComponent("inventory")?.container
        if (container){
            let isAvailable = false
            if (container.emptySlotsCount > 0) isAvailable = true
            if (!isAvailable){
                for (let i = 0; i < container.size; i++){
                    const thisItem = container.getItem(i)
                    if (thisItem?.typeId == itemStack?.typeId && thisItem.amount + itemStack?.amount <= thisItem?.maxAmount){
                        isAvailable = true
                    }
                }
            }
            if (isAvailable){
                container.addItem(itemStack)
                item.remove()
            }
        }
    }
    if (on){
        const items = block.dimension.getEntities({type:'minecraft:item', location:block.center(), maxDistance:block.getRedstonePower()})
        if (items){
            for (const item of items){
                if (item.dimension.getBlock(item.location).below()?.typeId != 'vtng_rt:ender_hopper'){
                    item.dimension.playSound('mob.endermen.portal', item.location)
                    item.dimension.spawnParticle('vtng_rt:ender_out', item.location)
                    block.dimension.spawnParticle('vtng_rt:ender_out', {x:block.center().x, y:block.center().y+0.4, z:block.center().z})
                    item.teleport({x:block.center().x, y:block.center().y+0.4, z:block.center().z})
                    break
                }
            }
        }
    }
    if (on != block.permutation.getState('vtng_rt:on')) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}