import { system } from "@minecraft/server";
import { decreaseDurability } from "../utils/durability.js";

const woodTypes = {
  "acacia": "wood",
  "birch": "wood", 
  "cherry": "cherry_wood",
  "crimson": "stem",
  "dark_oak": "wood",
  "jungle": "wood",
  "mangrove": "wood",
  "oak": "wood",
  "spruce": "wood",
  "pale_oak": "wood",
  "warped": "stem",
  "bamboo": "bamboo_wood"
}

// Handle custom axe create stripped wood
export function handleCustomAxe(block, player, location) {
  const blockId = block.typeId.split(":")[1];
  let woodType = blockId.split("_")[0];
  
  if(woodType == "pale") {
    woodType = "pale_oak"
  }
  if (!woodTypes[woodType]) return;

  const sound = woodTypes[woodType];
  const currentBlock = player.dimension.getBlock(location)
  const pillarAxis = currentBlock.permutation.getState("pillar_axis")

  if (blockId.endsWith("_wood")) {
    system.run(() => {

      player.runCommand(`/setblock ${location.x} ${location.y} ${location.z} stripped_${woodType}_wood["pillar_axis"="${pillarAxis}"]`);
      player.runCommand(`/playsound ${sound === 'cherry_wood' ? 'step' : 'use'}.${sound} @s`);
      decreaseDurability(player);
    });
    return;
  }

  if (blockId.endsWith("_log") || blockId.endsWith("_stem") || 
      blockId.endsWith("_hyphae") || blockId.endsWith("_block")) {
    system.run(() => {
      player.runCommand(`/setblock ${location.x} ${location.y} ${location.z} stripped_${blockId}["pillar_axis"="${pillarAxis}"]`);
      player.runCommand(`/playsound ${sound === 'cherry_wood' ? 'step' : 'use'}.${sound} @s`);
      decreaseDurability(player);
    });
    return;
  }
}


// Create farmland
export function handleCustomHoe(block, player, location) {
  player.runCommand(`/setblock ${location.x} ${location.y} ${location.z} farmland`);
  player.runCommand("/playsound use.gravel @s");
  decreaseDurability(player);
}

// Fire extinguishing and creating grass path
export function handleCustomShovel(block, player, location) {
  if (block.typeId == "minecraft:campfire" || block.typeId == "minecraft:soul_campfire") {
    if (block.permutation.getState("extinguished")) return
    player.runCommand(`/setblock ${location.x} ${location.y} ${location.z} ${block.typeId} ["extinguished"=true]`)
    decreaseDurability(player)
    player.runCommand(`/playsound random.fizz @s ${location.x} ${location.y} ${location.z} 0.5 2.0`)
    return
  }
  player.runCommand(`/setblock ${location.x} ${location.y} ${location.z} grass_path`)
  player.runCommand("/playsound use.gravel @s")
  decreaseDurability(player)
}
