import {
  world,
  system,
  EntityComponentTypes,
  EquipmentSlot,
} from "@minecraft/server";
import { getBuddyPartIndex } from "./getBuddyPart";

const playerCooldown = new Map();

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  const player = data.player;

  const currentTick = system.currentTick;
  const previousTick = playerCooldown.get(player.id) ?? 0;

  if (currentTick - previousTick < 10) return;
  playerCooldown.set(player.id, currentTick);

  const equippedItem = player.getComponent(EntityComponentTypes.Equippable);
  const slotMainHand = equippedItem.getEquipment(EquipmentSlot.Mainhand);

  const buddyPartMatch = getBuddyPartIndex(slotMainHand?.typeId);

  if (buddyPartMatch) {
    system.run(() => {
      equippedItem.setEquipment(EquipmentSlot.Mainhand, undefined);

      let targetBlock;

      switch (data.blockFace) {
        case "Up":
          targetBlock = data.block.above();
          break;
        case "Down":
          targetBlock = data.block.below();
          break;
        case "North":
          targetBlock = data.block.north();
          break;
        case "South":
          targetBlock = data.block.south();
          break;
        case "East":
          targetBlock = data.block.east();
          break;
        case "West":
          targetBlock = data.block.west();
          break;
      }

      const buddy_builder = player.dimension.spawnEntity(
        "arcedge_bap:buddy_builder",
        targetBlock.center(),
      );

      let partsLeftNeeded = ["Head", "Torso", "Legs"]

      switch (buddyPartMatch.type) {
        case "head":
          buddy_builder.setProperty("arcedge_bap:head_part", buddyPartMatch.index + 1);
          partsLeftNeeded.splice(0, 1);
          break;
        case "torso":
          buddy_builder.setProperty("arcedge_bap:torso_part", buddyPartMatch.index + 1);
          partsLeftNeeded.splice(1, 1);
          break;
        case "legs":
          buddy_builder.setProperty("arcedge_bap:legs_part", buddyPartMatch.index + 1);
          partsLeftNeeded.splice(2, 1);
          break;
      }

      player.playSound('note.bell')

      buddy_builder.nameTag = "Build your buddy!\n§a1§r/3 Parts";
      
      if (player.getDynamicProperty("first_buddy_builder_interact_default") == false) {
        player.sendMessage([
          { translate: "arcedge_bap.buddy.buddy_builder.placed", with: partsLeftNeeded },
        ]);
        player.setDynamicProperty("first_buddy_builder_interact_default", true)
      }
    });
  }
});
