import * as mc from "@minecraft/server"
import * as mcui from "@minecraft/server-ui"
import * as racoAPI from "../raco-API"
import { vanillaRecipes } from "./recipes"
import {hasRedstonePower} from "../hasRedstonePower"

export function uncrafterTick(block){
    if (block?.typeId == 'vtng_rt:uncrafter'){
        const hasPower = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'].filter(d => d !== block.permutation.getState('minecraft:cardinal_direction')), true);
        //console.warn(hasPower)
        if (hasPower){
            if (block.permutation.getState('vtng_rt:on') == false){
                const faces = [
                    'north',
                    'south',
                    'west',
                    'east',
                    'above'
                ]
                const direction = block.permutation.getState('minecraft:cardinal_direction')
                const facing = racoAPI.blockFaceToDirection(racoAPI.numToDirection(block.above().permutation.getState('facing_direction')))
                if (block.above()?.typeId == 'minecraft:hopper' && (facing == 'below' || facing == 'above')){
                    const hopperContainer = block.above().getComponent('inventory')?.container
                    for (let i = 0; i < hopperContainer.size; i++){
                        const thisItem = hopperContainer.getItem(i)
                        if (uncraft(thisItem, block, direction)){
                            racoAPI.clearItem(hopperContainer, i, vanillaRecipes[thisItem.typeId].amount)
                            break
                        }
                    }
                } else {
                    const entities = block.dimension.getEntities({type:'minecraft:item', location:block?.above()?.center(), maxDistance:0.7})
                    for (const entity of entities){
                        const thisItem = entity.getComponent('minecraft:item')?.itemStack
                        if (thisItem){
                            if (uncraft(entity.getComponent('minecraft:item')?.itemStack, block, direction)){
                                if (thisItem.amount > 1){
                                    const newItem = thisItem
                                    newItem.amount--
                                    const dropItem = entity.dimension.spawnItem(newItem, entity.location)
                                    dropItem.teleport(entity.location)
                                    entity.remove()
                                } else if (thisItem.amount == 1){
                                    entity.remove()
                                }
                                break
                            }
                        }
                    }
                }
                racoAPI.setPermutation(block, 'vtng_rt:on', true)
            }
        } else 
        if (block.permutation.getState('vtng_rt:on') == true){
            racoAPI.setPermutation(block, 'vtng_rt:on', false)
        }
        if (block.permutation.getState('vtng_rt:on') == true){
        }
    }
}
function uncraft(thisItem, block, direction){
    if (thisItem?.typeId && vanillaRecipes[thisItem?.typeId]){
        if (thisItem.amount >= vanillaRecipes[thisItem.typeId].amount){
            if (vanillaRecipes[thisItem.typeId].ingredientes.length > 0 && vanillaRecipes[thisItem.typeId].table == 'crafting_table'){
                let index = 0
                let itensMax = vanillaRecipes[thisItem.typeId]?.ingredientes?.length
                if (thisItem?.getComponent("minecraft:durability")){
                    const durability = thisItem?.getComponent("minecraft:durability")
                    const durabilityPercent = (durability.maxDurability-durability.damage)/durability.maxDurability
                    itensMax = Math.floor(durabilityPercent*vanillaRecipes[thisItem.typeId]?.ingredientes?.length)
                }
                for (const dropItem of vanillaRecipes[thisItem.typeId].ingredientes){
                    index++
                    if (index <= itensMax){
                        //block.dimension.spawnItem(new mc.ItemStack(dropItem), block[direction]())
                        block.dimension.playSound("block.click", block.center())
                        let loc = block.center()
                        if (direction == 'north') loc = racoAPI.operationWithVectorMINUS(loc, 0, 0, 0.4)
                        if (direction == 'south') loc = racoAPI.operationWithVectorPLUS(loc, 0, 0, 0.4)
                        if (direction == 'west') loc = racoAPI.operationWithVectorMINUS(loc, 0.4, 0, 0)
                        if (direction == 'east') loc = racoAPI.operationWithVectorPLUS(loc, 0.4, 0, 0)
                        try {
                            let itemSpawned = block.dimension.spawnItem(new mc.ItemStack(dropItem), loc)
                            let impulseLoc = racoAPI.calculateRelativeVector(racoAPI.blockFloorCenter(block), loc)
                            block.dimension.spawnParticle(`vtng_rt:uncrafter_smoke_${racoAPI.invertFace(direction)}`, block.center())
                            mc.system.runTimeout(()=>{try {itemSpawned.applyImpulse(impulseLoc)} catch (error){}},1)
                        } catch (error){}
                    }
                }
                return true
            }
        }
    }
}