import { BlockPermutation, TimeOfDay, system, world, ItemStack, StructureAnimationMode, StructureRotation, StructureSaveMode } from "@minecraft/server";
import { checkBelowEntityDespawn, getStringBefore, checkLocation, getEntityRotation, getLocationbyFacingBlock, stringBetween, getGamemode, getElementPosition, getElementPositionArrayWithObjects } from "./helpers";
import { cameraCutscene } from "../events/camera";
import { ModalFormData, ActionFormData } from "@minecraft/server-ui";

export class signHandler {
  static initialized = false;
  constructor() {
    this.initialize();
  }

  initialize() {
    if (!signHandler.initialized) {
      signHandler.initialized = true;
      this.processSubscriptions();
    } else {
    }
  }
  processSubscriptions() {
    let curTick = 0;
    const INIT_TIME = 0;

    system.runInterval(() => {
      try {
        if (curTick > INIT_TIME) {
          const allPlayers = world.getAllPlayers();
          allPlayers.forEach((player) => {
            if (!player.isValid()) return;
            else {
              checkBelowEntityDespawn(player, "sign");
            }
          });
        }
        curTick++;
      } catch (e) {
        console.warn(e);
      }
    }, 10);
    world.afterEvents.playerInteractWithEntity.subscribe((event) => {
      const player = event.player;
      const typeId = player.typeId;
      if (typeId !== "minecraft:player") {
        return;
      }
      if (event.target.typeId.includes("hb_cb:sign")) {
        const sign = event.target;
        this.interactAbility(player, sign);
      } else return;
    });
    world.afterEvents.itemUse.subscribe((event) => {
      const player = event.source;
      const typeId = player.typeId;
      if (typeId !== "minecraft:player") {
        return;
      }
      const holdingItem = player.getComponent("equippable").getEquipment("Mainhand");
      if (holdingItem == undefined) {
        return;
      }
      if (holdingItem.typeId.includes("hb_cb:sign")) this.spawnsign(player, holdingItem);
    });
    system.afterEvents.scriptEventReceive.subscribe((event) => {
      if (event.sourceEntity == undefined) return;
      else {
        if (event.sourceEntity.typeId.includes("hb_cb:") && event.sourceEntity.typeId.includes("sign")) {
          let sign = event.sourceEntity;
          switch (event.id) {
            case "hb_cb:despawn_tick_hit_trigger":
              if (sign.getProperty("hb_cb:despawn_tick") < 4) {
                sign.runCommand("/playsound hb_cb:sign_hit @a[r=10] ~~~ 1 1");
                sign.runCommand("/playanimation @s animation.hb_cb.sign.break");
                sign.runCommand("/event entity @s hb_cb:despawn_tick_hit");
              }
              break;
            case "hb_cb:sign_despawn":
              this.despawnsign(sign);
              break;
            default:
              break;
          }
        }
      }
    });
  }
  interactAbility(player, sign) {
    // world.sendMessage("sign interact");
    const form = new ModalFormData();
    form.title("hb_cb.sign.ui.title");
    form.dropdown("hb_cb.sign.ui.dropdown.title", [{ translate: "hb_cb.sign.ui.text_0" }, { translate: "hb_cb.sign.ui.text_1" }, { translate: "hb_cb.sign.ui.text_2" }, { translate: "hb_cb.sign.ui.text_3" }, { translate: "hb_cb.sign.ui.text_4" }, { translate: "hb_cb.sign.ui.text_5" }, { translate: "hb_cb.sign.ui.text_6" }, { translate: "hb_cb.sign.ui.text_7" }, { translate: "hb_cb.sign.ui.text_8" }], sign.getProperty("hb_cb:sign_text") ?? 0);
    form.submitButton("hb_cb.sign.ui.change_sign");
    form.show(player).then((data) => {
      if (data.formValues == undefined) return;
      // world.sendMessage(data.formValues[0].toString());
      sign.setProperty("hb_cb:sign_text", data.formValues[0]);
    });
  }

  spawnsign(player, item) {
    const raycastBlock = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: false, maxDistance: 8 });
    if (raycastBlock == undefined) return;
    else {
      let gamemodeCreative = getGamemode(player, 1);
      const location = raycastBlock.block.location;
      const face = raycastBlock.face;

      let yRotation = getEntityRotation(player);
      let orientation;
      switch (yRotation) {
        case 0:
          orientation = "north";
          break;
        case 90:
          orientation = "east";
          break;
        case 180:
          orientation = "south";
          break;
        case 270:
          orientation = "west";
          break;

        default:
          break;
      }

      let placeLoc = getLocationbyFacingBlock(face, location);
      if (checkLocation(placeLoc, player, placeLoc, 1)) return;
      let block = world.getDimension(player.dimension.id).getBlock({ x: placeLoc.x, y: placeLoc.y, z: placeLoc.z });
      let block2 = world.getDimension(player.dimension.id).getBlock({ x: placeLoc.x, y: placeLoc.y + 1, z: placeLoc.z });
      block.setType("hb_cb:sign_block");
      block2.setType("hb_cb:sign_block");
      // world.sendMessage(block2.typeId);
      // world.sendMessage(block2.permutation.getState("minecraft:block_face"));

      // world.sendMessage(orientation);
      block.setPermutation(
        BlockPermutation.resolve("hb_cb:sign_block", {
          "minecraft:block_face": orientation,
        })
      );
      block2.setPermutation(
        BlockPermutation.resolve("hb_cb:sign_block", {
          "minecraft:block_face": orientation,
        })
      );

      // let sign = world.getDimension(player.dimension.id).spawnEntity(item.typeId, placeLoc);
      // world.sendMessage(getStringBefore(item.typeId, "_item"));
      player.runCommand("/summon " + getStringBefore(item.typeId, "_item") + " " + placeLoc.x.toString() + " " + placeLoc.y.toString() + " " + placeLoc.z.toString() + " " + yRotation.toString() + " 0");
      if (!gamemodeCreative) {
        player.runCommand("/clear @s " + item.typeId + " 0 1");
      }
    }
  }

  despawnsign(sign) {
    sign.runCommand("/playanimation @s animation.hb_cb.sign.despawn");
    system.waitTicks(1).then(() => {
      if (sign.hasTag("hb_cb:start_block_despawn")) {
        sign.teleport({ x: sign.location.x, y: sign.location.y + 0.5, z: sign.location.z });
      }
      let block = world.getDimension(sign.dimension.id).getBlock({ x: sign.location.x, y: sign.location.y, z: sign.location.z });
      let block2 = world.getDimension(sign.dimension.id).getBlock({ x: sign.location.x, y: sign.location.y + 1, z: sign.location.z });
      block.setType("minecraft:air");
      block2.setType("minecraft:air");
      let spawnedItem = new ItemStack(sign.typeId + "_item");
      world.getDimension(sign.dimension.id).spawnItem(spawnedItem, sign.location);
      sign.remove();
    });
  }
}
