import { system, world, BlockVolume, ItemStack } from "@minecraft/server";

export function bannedWitherSkullPodest() {
  world.afterEvents.entityHitEntity.subscribe(handleWitherSkullPodestHit);
  world.afterEvents.playerInteractWithEntity.subscribe(handleWitherSkullPodestInteract);

  function handleWitherSkullPodestInteract(event) {
    const player = event.player;
    const target = event.target;
    if (!target.isValid()) {
      return;
    }
    if (player.typeId == "minecraft:player") {
      if (target.typeId.includes("hb_hr:banned_wither_skull_podest")) {
        const hasSkull = target.getProperty("hb_hr:has_skull");
        if (hasSkull == false) return;
        else {
          let itemName = target.typeId.includes("b1") ? new ItemStack("hb_hr:banned_wither_skull_b1_block") : target.typeId.includes("b2") ? new ItemStack("hb_hr:banned_wither_skull_b2_block") : target.typeId.includes("b3") ? new ItemStack("hb_hr:banned_wither_skull_b3_block") : null;
          const newItem = world.getDimension(target.dimension.id).spawnItem(itemName, { x: target.location.x, y: target.location.y + 1, z: target.location.z });
          newItem.clearVelocity();
          target.setProperty("hb_hr:has_skull", false);
        }
      }
    }
  }
  function handleWitherSkullPodestHit(event) {
    const damager = event.damagingEntity;
    const hit_entity = event.hitEntity;
    if (!hit_entity.isValid()) {
      return;
    }
    if (damager.typeId == "minecraft:player") {
      // case for not holding any item aka air

      if (hit_entity.typeId.includes("hb_hr:banned_wither_skull_podest")) {
        const hasSkull = hit_entity.getProperty("hb_hr:has_skull");
        if (hasSkull == true) {
          // let itemName;
          let itemName = hit_entity.typeId.includes("b1") ? new ItemStack("hb_hr:banned_wither_skull_b1_block") : hit_entity.typeId.includes("b2") ? new ItemStack("hb_hr:banned_wither_skull_b2_block") : hit_entity.typeId.includes("b3") ? new ItemStack("hb_hr:banned_wither_skull_b3_block") : null;

          const newItem = world.getDimension(hit_entity.dimension.id).spawnItem(itemName, { x: hit_entity.location.x, y: hit_entity.location.y + 1, z: hit_entity.location.z });
          newItem.clearVelocity();
          hit_entity.setProperty("hb_hr:has_skull", false);
          return;
        } else {
          const currentHits = hit_entity.getProperty("hb_hr:despawn_tick");
          if (currentHits < 4) {
            hit_entity.setProperty("hb_hr:despawn_tick", currentHits + 1);
            hit_entity.runCommand("/playanimation @s break");
          }
          if (currentHits >= 4) {
            hit_entity.runCommand("/function hb/hr/despawn_wither_podest");
            hit_entity.remove();
          }
        }
      }
    }
  }
}
