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




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

  initialize() {
    if (!benchHandler.initialized) {
      benchHandler.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, "bench");
            }
          });
        }
        curTick++;
      } catch (e) {
        console.warn(e);
      }
    }, 0);

    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 == "hb_cb:bench_item") this.spawnBench(player, holdingItem);
    });
    system.afterEvents.scriptEventReceive.subscribe((event) => {
      if (event.sourceEntity == undefined) return;
      else {
        if (event.sourceEntity.typeId.includes("hb_cb:") && event.sourceEntity.typeId.includes("bench")) {
          let bench = event.sourceEntity;
          switch (event.id) {
            case "hb_cb:despawn_tick_hit_trigger":
              if (bench.getProperty("hb_cb:despawn_tick") < 4) {
                bench.runCommand("/playsound step.wood @a[r=10] ~~~ 1 1");
                bench.runCommand("/playanimation @s animation.hb_cb.bench.break");
                bench.runCommand("/event entity @s hb_cb:despawn_tick_hit");
              }
              break;
            case "hb_cb:bench_despawn":
              this.despawnBench(bench);
              break;
            default:
              break;
          }
        }
      }
    });
  }

  spawnBench(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 placeLoc = getLocationbyFacingBlock(face, location);
      if (checkLocation(placeLoc, player, placeLoc, 0)) return;

      // let bench = world.getDimension(player.dimension.id).spawnEntity(item.typeId, placeLoc);
      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 block = world.getDimension(player.dimension.id).getBlock({ x: placeLoc.x, y: placeLoc.y, z: placeLoc.z });
      const { leftBlock, rightBlock } = getSideBlockLocations(orientation, block);

      let leftBlockPlace = world.getDimension(player.dimension.id).getBlock({ x: leftBlock.x, y: leftBlock.y, z: leftBlock.z });
      let rightBlockPlace = world.getDimension(player.dimension.id).getBlock({ x: rightBlock.x, y: rightBlock.y, z: rightBlock.z });
      if (block.typeId != "minecraft:air" || leftBlockPlace.typeId != "minecraft:air" || rightBlockPlace.typeId != "minecraft:air") {
        player.runCommand('/tellraw @s {"rawtext": [{"translate":"hb_cb.place_entity_error"}]}');
        return;
      }
      // Place all three blocks
      [block, leftBlockPlace, rightBlockPlace].forEach((blockPos) => {
        blockPos.setType("hb_cb:bench_block");
        blockPos.setPermutation(
          BlockPermutation.resolve("hb_cb:bench_block", {
            "minecraft:block_face": orientation,
          })
        );
      });

      player.runCommand("/playsound step.wood @a[r=10] ~~~ 1 1");
      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");
      }
    }
  }

  despawnBench(bench) {
    bench.runCommand("/playanimation @s animation.hb_cb.bench.despawn");
    system.waitTicks(1).then(() => {
      let yRotation = getEntityRotation(bench);
      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;
      }
      if (bench.hasTag("hb_cb:start_block_despawn")) {
        bench.teleport({ x: bench.location.x, y: bench.location.y + 0.5, z: bench.location.z });
      }
      let block = world.getDimension(bench.dimension.id).getBlock({ x: bench.location.x, y: bench.location.y, z: bench.location.z });
      const { leftBlock, rightBlock } = getSideBlockLocations(orientation, block);
      let leftBlockPlace = world.getDimension(bench.dimension.id).getBlock({ x: leftBlock.x, y: leftBlock.y, z: leftBlock.z });
      let rightBlockPlace = world.getDimension(bench.dimension.id).getBlock({ x: rightBlock.x, y: rightBlock.y, z: rightBlock.z });

      // Place all three blocks
      [block, leftBlockPlace, rightBlockPlace].forEach((blockPos) => {
        blockPos.setType("minecraft:air");
      });

      let spawnedItem = new ItemStack("hb_cb:bench_item");
      world.getDimension(bench.dimension.id).spawnItem(spawnedItem, bench.location);
      bench.remove();
    });
  }
}
