import * as MC from "@minecraft/server";
import { run, onItem, onInteract } from "./utilities";

run((players) => {
  players.forEach((player) => {
    const mainHand = player
      .getComponent("minecraft:equippable")
      .getEquipmentSlot("Mainhand")
      .getItem();
    const offHand = player
      .getComponent("minecraft:equippable")
      .getEquipmentSlot("Offhand")
      .getItem();

    const banishingRites = player.hasTag("chronicoverride_llc:banishing_rites");
    const hasWhisperingDoll = player.hasTag(
      "chronicoverride_llc:whispering_doll"
    );

    if (mainHand || offHand) {
      if (
        !banishingRites &&
        offHand?.typeId === "chronicoverride_llc:banishing_rites"
      ) {
        player.addTag("chronicoverride_llc:banishing_rites");
      }
      if (
        banishingRites &&
        offHand?.typeId !== "chronicoverride_llc:banishing_rites"
      ) {
        player.removeTag("chronicoverride_llc:banishing_rites");
      }
      if (
        (!hasWhisperingDoll &&
          mainHand?.typeId === "chronicoverride_llc:whispering_doll") ||
        offHand?.typeId === "chronicoverride_llc:whispering_doll"
      ) {
        player.addTag("chronicoverride_llc:whispering_doll");
        player.runCommand(`effect @s speed infinite 0 true`);
      }
      if (
        hasWhisperingDoll &&
        mainHand?.typeId !== "chronicoverride_llc:whispering_doll" &&
        offHand?.typeId !== "chronicoverride_llc:whispering_doll"
      ) {
        player.removeTag("chronicoverride_llc:whispering_doll");
        player.runCommand(`effect @s clear speed`);
      }
    }
    if (!mainHand && !offHand) {
      if (hasWhisperingDoll) {
        player.removeTag("chronicoverride_llc:whispering_doll");
        player.runCommand(`effect @s clear speed`);
      }
      if (banishingRites) {
        player.removeTag("chronicoverride_llc:banishing_rites");
      }
    }
  });
}, 10);

onItem(({ itemStack, source }) => {
  if (itemStack.typeId === "chronicoverride_llc:widows_web_potion") {
    const cooldown = itemStack.getComponent("minecraft:cooldown");
    if (
      cooldown.getCooldownTicksRemaining(source) ===
      cooldown.cooldownTicks - 1
    ) {
      source.runCommand(`playsound mob.witch.throw @s`);
    }
  }
});

onInteract((event) => {
  const { block, blockFace, itemStack, player } = event;
  if (itemStack?.typeId === "chronicoverride_llc:dreamcatcher") {
    event.cancel = true;
    if (blockFace !== "Down" && blockFace !== "Up" && !block.isLiquid) {
      const blockOnPlace =
        blockFace === "North"
          ? block.north(1)
          : blockFace === "East"
            ? block.east(1)
            : blockFace === "South"
              ? block.south(1)
              : block.west(1);
      if (blockOnPlace.above(1).isAir) {
        MC.system.run(() => {
          const location = blockOnPlace.above(1).bottomCenter();
          if (blockFace === "North") {
            block.dimension.runCommand(
              `summon chronicoverride_llc:dreamcatcher ${location.x} ${location.y} ${location.z} 180 ~`
            );
          }
          if (blockFace === "East") {
            block.dimension.runCommand(
              `summon chronicoverride_llc:dreamcatcher ${location.x} ${location.y} ${location.z} -90 ~`
            );
          }
          if (blockFace === "South") {
            block.dimension.runCommand(
              `summon chronicoverride_llc:dreamcatcher ${location.x} ${location.y} ${location.z} 0 ~`
            );
          }
          if (blockFace === "West") {
            block.dimension.runCommand(
              `summon chronicoverride_llc:dreamcatcher ${location.x} ${location.y} ${location.z} -270 ~`
            );
          }
          player.runCommand("clear @s chronicoverride_llc:dreamcatcher 0 1");
        });
      } else {
        MC.system.run(() => {
          player.runCommand(
            `tellraw @s {"rawtext":[{"text":"§cThere is not enough space to place the Dreamcatcher here."}]}`
          );
        });
      }
    } else {
      MC.system.run(() => {
        player.runCommand(
          `tellraw @s {"rawtext":[{"text":"§cYou cannot place the Dreamcatcher here."}]}`
        );
      });
    }
  }
});

MC.system.beforeEvents.startup.subscribe((initEvent) => {
  initEvent.itemComponentRegistry.registerCustomComponent(
    "chronicoverride_llc:shadow_salve",
    {
      onConsume({ source }) {
        source.runCommand(`effect @s invisibility 120 0 false`);
      },
    }
  );
});

MC.system.beforeEvents.startup.subscribe((initEvent) => {
  initEvent.blockComponentRegistry.registerCustomComponent(
    "chronicoverride_llc:shade_candle",
    {
      onPlace({ block }) {
        block.dimension.runCommand(
          `summon chronicoverride_llc:shade_candle ${block.location.x} ${block.location.y} ${block.location.z}`
        );
      },
      onPlayerDestroy({ block }) {
        const shade_candle = block.dimension.getEntities({
          type: "chronicoverride_llc:shade_candle",
          location: block.location,
          maxDistance: 1.5,
          closest: 1,
        })[0];
        if (shade_candle) shade_candle.remove();
      },
    }
  );
});
