import { Block, EquipmentSlot, ItemStack, system } from "@minecraft/server";
import { ItemTags } from "../utils/itemConstants";
import { Piki, SoundsIds } from "../../utils/typingConstants";
import { CustomBlockTags } from "../../blocks/utils/blockTags";
import { multiClicking } from "../../utils/systemHelper";
import { CommandHelper } from "../../utils/commandHelper";
import { BlockStateNames } from "../../blocks/utils/blockConstants";
import { CUSTOM_DURABILITY } from "./customDurability";
import { CustomItemTags } from "../utils/itemTags";

export const CUSTOM_BARKS = {
    /**
     * 
     * @param {ItemStack} itemStack 
     * @param {Block} block 
     * @returns 
     */
    shouldDropBark(itemStack, block, source) {
        if (!itemStack.hasTag(ItemTags.isAxe)) return;
        if (multiClicking(source)) return
        if (CustomBlockTags.isStripped(block)) return
        return CustomBlockTags.dropsCustomBark(block)
    },
    /**
     * 
     * @param {Block} block 
     */
    dropBark(block, source, itemStack) {
        const barkType = this._getBarkType(block.typeId) 
        const lootFile = this._getLootFilePath(barkType) 
        const stripped = this._getStrippedType(block.typeId) 
        const command = CommandHelper.generateSpawnLootCommand(block.location, lootFile)
        system.run(() => {
            try {
                block.dimension.runCommandAsync(command)
                if (CustomBlockTags.isCustom(block) || CustomItemTags.isCustom(itemStack)) {
                    block.dimension.playSound(SoundsIds.useWood, block.location)
                    CUSTOM_DURABILITY.damageItem(source, EquipmentSlot.Mainhand, true)
                }
                if (!CustomBlockTags.isCustom(block)) return
                const rotationState = block.permutation.getState(BlockStateNames.blockFace)
                block.setType(stripped)
                const copiedRotation = block.permutation.withState(BlockStateNames.blockFace, rotationState)
                block.setPermutation(copiedRotation)
            } catch (error) {
                // testing.error(error)
            }   
        })
    },    
    
    /**
     * HACK:
     */
    _getStrippedType(blockTypeId) {
        return blockTypeId + "_stripped"
    },
    /**
     * HACK:
     */
    _getLootFilePath(barkTypeId) {
        return Piki.blockLootsPath + barkTypeId + "_log"
        
    },  
    /**
     * HACK: 
     * @param {string} blockTypeId 
     */
    _getBarkType(blockTypeId) {
        return blockTypeId
            .replace(Piki.minecraftNamespace, "")
            .replace(Piki.namespace, "")
            .replace("_wood", "")
            .replace("_log", "")
            .replace("_painted", "")
    }
}