
import { Block, Direction } from "@minecraft/server";
import { Piki } from "../../utils/typingConstants";
import { WorldHelper } from "../../world/utils/worldHelper";
import { EntityTypeIds } from "../../entities/utils/entityTypesIds";

export class BlockHelper {

    /**
     * 
     * @param {Block} block 
     * @param {Direction} blockFace 
     * @returns 
     */
    static getBlockFromFace(block, blockFace) {
        switch (blockFace) {
            case "Up": return block.above(); 
            case "East": return block.east(); 
            case "West": return block.west(); 
            case "North": return block.north(); 
            case "South": return block.south();
            case "Down": return block.below()
        }
    }

    /**
     * 
     * @param {Block} block 
     */
    static getDummy(block) {
        if (!block) return undefined
        const {x, y, z} = block.location
        const dummy = block.dimension.getEntities({
            location: WorldHelper.createNewLocation(x + 0.5, y, z + 0.5), 
            closest: 1,
            maxDistance: 0,
            type: EntityTypeIds.dummy
        })
        if (dummy.length > 0) return dummy[0]
        else return undefined
    }

    /**
     * 
     * Check if block is listed in the array using its typeId or tag
     * @param {string[]} array 
     * @param {Block} block 
     */
    static isBlockListed(array, block) {
        for (const element of array) {
            if (element == block.typeId) return true
            if (element.includes("#") && block.hasTag(element.replace("#", ""))) return true
            if (element.includes(".") && block.typeId.endsWith(element.replace(".", ""))) return true
            if (element.includes("/") && block.typeId.startsWith(element.replace("/", ""))) return true
        }
        return false
    }

    /**
     * Gets the real block id of an item placer
     * @param {string} itemStackId 
     * @returns The ItemStack Id without a `_placer` suffix
     */
    static getPlacerRealBlockId(itemStackId) {
        return itemStackId.replace("_placer", "")
    }

    /**
     * Treats block tags as key and value pair and search for tag that starts with `tagPrefix:` then returns the rest
     * @example `piki_beyondsurvival:correct_tool:pickaxe` returns `pickaxe`
     * @note Tag prefixes can be listed in `BlockValuedTagsKey`
     * 
     * @param {Block} block 
     * @param {string} tagPrefix 
     */
    static getBlockTagValue(block, tagPrefix) {
        const completeTagPrefix = Piki.namespace + tagPrefix + ":"
        for (const tag of block.getTags()) {
            if (!tag.startsWith(completeTagPrefix)) continue
            return tag.split(completeTagPrefix)[1]
        }
    }
}