import * as mc from "mojang-minecraft"
export function isRedstonePowered(location, dimension) {
    const blocks = [
        dimension.getBlock(new mc.BlockLocation(location.x, location.y, location.z + 1)),
        dimension.getBlock(new mc.BlockLocation(location.x - 1, location.y, location.z)),
        dimension.getBlock(new mc.BlockLocation(location.x, location.y, location.z - 1)),
        dimension.getBlock(new mc.BlockLocation(location.x + 1, location.y, location.z)),
        dimension.getBlock(new mc.BlockLocation(location.x, location.y - 1, location.z)),
        dimension.getBlock(new mc.BlockLocation(location.x, location.y + 1, location.z)),
    ]

    for (let i = 0; i < blocks.length; i++) {
        const block = blocks[i]

        const redstoneSignal = block.permutation.getProperty(mc.BlockProperties.redstoneSignal)
        const poweredBit = block.permutation.getProperty(mc.BlockProperties.poweredBit)

        if (
            (redstoneSignal && redstoneSignal.value > 0) ||
            (poweredBit && poweredBit.value) ||
            (block.id == 'minecraft:lever' && block.permutation.getProperty(mc.BlockProperties.openBit).value) ||
            block.id == 'minecraft:redstone_block' ||
            block.id == 'minecraft:redstone_torch' ||
            (block.id == 'minecraft:powered_repeater' && block.permutation.getProperty(mc.BlockProperties.direction).value == i) ||
            block.id == 'minecraft:powered_comparator'
        ) return true
    }

    return false
}
export function emitRedstoneSignal(location, dimension) {
    const blocks = [
        dimension.getBlock(new mc.BlockLocation(location.x, location.y, location.z - 1)),
        dimension.getBlock(new mc.BlockLocation(location.x + 1, location.y, location.z)),
        dimension.getBlock(new mc.BlockLocation(location.x, location.y, location.z + 1)),
        dimension.getBlock(new mc.BlockLocation(location.x - 1, location.y, location.z))
    ]

    for (let i = 0; i < blocks.length; i++) {
        const block = blocks[i]

        if (block.id == 'minecraft:unpowered_repeater') {
            const direction = block.permutation.getProperty(mc.BlockProperties.direction).value
            if (direction != i) continue

            const delay = block.permutation.getProperty(mc.BlockProperties.repeaterDelay).value
            block.setType(mc.MinecraftBlockTypes.poweredRepeater)
            const permutation = block.permutation
            permutation.getProperty(mc.BlockProperties.direction).value = direction
            permutation.getProperty(mc.BlockProperties.repeaterDelay).value = delay
            block.setPermutation(permutation)
        }
    }
}
export function locationToBlockLocation(location) {
    return new mc.BlockLocation(Math.floor(location.x), Math.floor(location.y), Math.floor(location.z))
}