import { 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 { ActionFormData } from "@minecraft/server-ui";

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

  initialize() {
    if (!diamondPoppyHandler.initialized) {
      diamondPoppyHandler.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, "diamond_poppy");
              this.sneakAbility(player);
            }
          });
        }
        curTick++;
      } catch (e) {
        console.warn(e);
      }
    }, 0);

    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:") && event.target.typeId.includes("diamond_poppy")) {
        const diamondPoppy = event.target;
        this.interactAbility(player, diamondPoppy);
      } 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 == "hb_cb:diamond_poppy_item") this.spawnDiamondPoppy(player, holdingItem);
    });
    system.afterEvents.scriptEventReceive.subscribe((event) => {
      if (event.sourceEntity == undefined) return;
      else {
        if (event.sourceEntity.typeId.includes("hb_cb:") && event.sourceEntity.typeId.includes("diamond_poppy")) {
          let diamond_poppy = event.sourceEntity;
          switch (event.id) {
            case "hb_cb:despawn_tick_hit_trigger":
              if (diamond_poppy.getProperty("hb_cb:despawn_tick") < 4) {
                diamond_poppy.runCommand("/playsound use.nether_brick @a[r=10] ~~~ 1 1");
                diamond_poppy.runCommand("/playanimation @s animation.hb_cb.diamond_poppy.break");
                diamond_poppy.runCommand("/event entity @s hb_cb:despawn_tick_hit");
              }
              break;
            case "hb_cb:diamond_poppy_despawn":
              this.despawnDiamondPoppy(diamond_poppy);
              break;
            default:
              break;
          }
        }
      }
    });
  }

  sneakAbility(player) {
    const item = player.getComponent("equippable").getEquipment("Mainhand");
    const itemOffhand = player.getComponent("equippable").getEquipment("Offhand");
    // Proceed only if at least one of them is defined
    if (item !== undefined || itemOffhand !== undefined) {
      // Your code here will execute if either item or itemOffhand is defined
      // Add your additional logic here
      this.handleItem(item, player);
      this.handleItem(itemOffhand, player);
    }
  }
  interactAbility(player, diamond_poppy) {
    if (diamond_poppy.getProperty("hb_cb:cooldown")) return;
    player.runCommand("/playsound hb_cb:diamond_poppy_shot @a[r=10] ~~~ 1 1");
    diamond_poppy.runCommand("/event entity @s hb_cb:add_cooldown");
    player.addEffect("absorption", 200, { amplifier: 2, showParticles: false });
    player.addEffect("regeneration", 200, { amplifier: 2, showParticles: false });
    return;
  }

  handleItem(item, player) {
    if (!item) return; // Early exit if the item is undefined

    if (item.typeId == "hb_cb:diamond_poppy_item") {
      const cooldownComp = item.getComponent("cooldown");
      if (!cooldownComp) return;

      if (player.getItemCooldown(cooldownComp.cooldownCategory) > 0) return;

      if (player.isSneaking) {
        player.runCommand("/playsound hb_cb:diamond_poppy_shot @a[r=10] ~~~ 1 1");
        player.dimension.spawnParticle("hb_cb:diamond_poppy_active", { x: player.location.x, y: player.location.y + 0.3, z: player.location.z });
        player.dimension.spawnParticle("hb_cb:diamond_poppy_active_2_flipped", { x: player.location.x, y: player.location.y + 0.3, z: player.location.z });
        player.addEffect("absorption", 200, { amplifier: 2, showParticles: false });
        player.addEffect("regeneration", 200, { amplifier: 2, showParticles: false });
        cooldownComp.startCooldown(player);
      }
    } else return;
  }

  spawnDiamondPoppy(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 block = world.getDimension(player.dimension.id).getBlock({ x: placeLoc.x, y: placeLoc.y, z: placeLoc.z });
      block.setType("hb_cb:diamond_poppy_block");

      // let diamond_poppy = world.getDimension(player.dimension.id).spawnEntity(item.typeId, placeLoc);
      let yRotation = getEntityRotation(player);
      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");
      }
    }
  }

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