import * as mc from "@minecraft/server"
import * as racoAPI from "../raco-API"

export function randomHopperTick(block){
    const faces = [
        'north',
        'south',
        'west',
        'east'
    ]
    let myFaces = []
    for (const face of faces){
        racoAPI.setPermutation(block, `vtng_rt:${racoAPI.invertFace(face)}`, block[face]()?.getComponent('inventory')?.container ? true : false)
        if (block[face]()?.getComponent('inventory')?.container){
            myFaces.push(face)
        }
    }
    if (block.above()?.getComponent('inventory')?.container && myFaces?.length > 0){
        const container = block.above()?.getComponent('inventory')?.container
        for (let i = 0; i < container.size; i++){
            const thisItem = container.getItem(i)
            const array = shuffleArray(myFaces)
            let achou = false
            for (const thisFace of array){
                if (Math.random() > 0.5) continue;
                const thisBlock = block[thisFace]()
                const thisContainer = thisBlock?.getComponent('inventory')?.container
                if (thisContainer){
                    if (racoAPI.transferItem(container, thisContainer, i, 1)){
                        achou = true
                    }
                }
            }
            if (achou) break
        }
    } else {
        const itemsAbove = block.dimension.getEntities({type:"minecraft:item",  location:block.above().center(), maxDistance:0.6})
        for (const thisItemEntity of itemsAbove){
            const thisItem = thisItemEntity?.getComponent("minecraft:item").itemStack
            const array = shuffleArray(myFaces)
            let achou = false
            for (const thisFace of array){
                if (Math.random() > 0.5) continue;
                const thisBlock = block[thisFace]()
                const thisContainer = thisBlock?.getComponent('inventory')?.container
                if (thisContainer){
                    if (racoAPI.transferEntityItem(thisItemEntity, thisContainer, 1)){
                        achou = true
                    }
                }
            }
            if (achou) break
        }
    }
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }