import { Block, Entity, ItemStack, system } from "@minecraft/server";
import { arrayIncludes, testing } from "../../utils/systemHelper";
import { CommandHelper } from "../../utils/commandHelper";
import { BlockTypeIds } from "../../blocks/utils/blockConstants";
import { CustomBlockTags } from "../../blocks/utils/blockTags";
import { EntityHelper } from "../../entities/utils/entityHelper";

export const VENOMITE_TOOLS = {
    _venomBreakDelay: 3,
    _venomToolBreaks: {
        "piki_beyondsurvival:venomite_axe": CustomBlockTags.isVenomiteAxeBreakable,
        "piki_beyondsurvival:venomite_pickaxe": CustomBlockTags.isVenomitePickaxeBreakable,
        "piki_beyondsurvival:venomite_shovel": CustomBlockTags.isVenomiteShovelBreakable,
        "piki_beyondsurvival:venomite_hoe": CustomBlockTags.isVenomiteHoeBreakable,
        "piki_beyondsurvival:venomite_sword": CustomBlockTags.isVenomiteSwordBreakable
    },
    _venomBreakMethod: "destroy",
    _venomBreakDirections: [
        "above",
        "below",
        "east",
        "west",
        "north",
        "south"
    ],
    _attackEffect: EntityHelper.createEntityEffect("poison", 3, 0, true),
    
    isVenomiteTool: function(itemTypeId) {
        return arrayIncludes(Object.keys(this._venomToolBreaks), itemTypeId)
    },

    /**
     * 
     * @param {Block} block 
     * @param {ItemStack} itemStack
     */
    applyVenomBreak: function(block, itemStack) {
        // testing.info(`Applying Venomite Tool Break in ${this._venomBreakDelay} seconds`)

        /** @type {Block[]} */
        const breakBlocks = []
        for (const direction of this._venomBreakDirections) {
            const targetBlock = block[direction]()
            const filter = this._venomToolBreaks[itemStack.typeId]
            if (!targetBlock.isValid()) continue 
            if (!filter(targetBlock)) continue
            breakBlocks.push(targetBlock)
        }
    
        system.runTimeout(() => {
            let success = 0;
            for (const breakBlock of breakBlocks) {
                const {location, dimension} = breakBlock
                const command = CommandHelper.generateSetBlockCommand(location, BlockTypeIds.air, this._venomBreakMethod)
                dimension.runCommandAsync(command)
                success++
            }
            // testing.success("Broke", success, "blocks")
        }, this._venomBreakDelay * 20)
    },

    /**
     * 
     * @param {Entity} hitEntity 
     */
    applyAttackEffect(hitEntity) {
        const {effectType, duration, amplifier, showParticles} = this._attackEffect
        hitEntity.addEffect(effectType, duration, {amplifier: amplifier, showParticles: showParticles})
    }

}