import { EquipmentSlot, world } from '@minecraft/server'
import { EntityComponents as EComponents } from '../entities/utils/entityComponents'

const pickaxes = {
    "wooden_pickaxe": "wood",
    "stone_pickaxe": "stone",
    "iron_pickaxe": "iron",
    "golden_pickaxe": "gold",
    "diamond_pickaxe": "diamond",
    "netherite_pickaxe": "netherite"
}

const axes = {
    "wooden_axe": "wood",
    "stone_axe": "stone",
    "iron_axe": "iron",
    "golden_axe": "gold",
    "diamond_axe": "diamond",
    "netherite_axe": "netherite"
}

const shovels = {
    "wooden_shovel": "wood",
    "stone_shovel": "stone",
    "iron_shovel": "iron",
    "golden_shovel": "gold",
    "diamond_shovel": "diamond",
    "netherite_shovel": "netherite"
}

const hoes = {
    "wooden_hoe": "wood",
    "stone_hoe": "stone",
    "iron_hoe": "iron",
    "golden_hoe": "gold",
    "diamond_hoe": "diamond",
    "netherite_hoe": "netherite"
}

const CUSTOM_MINING_SPEED_TAG = "piki_beyondsurvival:custom_mining_speed"
const CORRECT_TOOLS_TAG_PREFIX = "piki_beyondsurvival:correct_tool:"
const TOOL_TIER_STATE = "piki_beyondsurvival:tool"

world.afterEvents.entityHitBlock.subscribe(eventData => {
    const block = eventData.hitBlock
    const player = eventData.damagingEntity

    if (!block.hasTag(CUSTOM_MINING_SPEED_TAG)) return

    const usingTool = EComponents.getEquippable(player).getEquipment(EquipmentSlot.Mainhand)
    const correctTool = block.getTags().find(tag => tag.startsWith(CORRECT_TOOLS_TAG_PREFIX)).split(CORRECT_TOOLS_TAG_PREFIX)[1]

    let tier

    switch (correctTool) {
        case 'pickaxe':
            tier = pickaxes[usingTool?.typeId.split(':')[1]]
            break
        case 'axe':
            tier = axes[usingTool?.typeId.split(':')[1]]
            break
        case 'shovel':
            tier = shovels[usingTool?.typeId.split(':')[1]]
            break
        case 'hoe':
            tier = hoes[usingTool?.typeId.split(':')[1]]
            break
    }

    block.setPermutation(block.permutation.withState(TOOL_TIER_STATE, tier ?? 'default'))
})