import { world, system, EquipmentSlot, EntityEquippableComponent, ItemStack, EntityInventoryComponent } from "@minecraft/server";
import { Bleeding, HammerBreak, HoeBreak, ShovelBreak, Sweep, Weakness, Weight, Contusion, Amputate, Fracture, Spear, AntiBurner, LoreManager, BackStabbing } from "./impl/exports";
import { detectItemOnInventory } from "./functions";

// Script entry

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const equipment = player.getComponent(EntityEquippableComponent.componentId);
    const mainHand = equipment.getEquipment(EquipmentSlot.Mainhand);
    const hasItemBarrier = detectItemOnInventory(player, "true:barrier")
    const playerInventoryComponentContainer = player.getComponent(EntityInventoryComponent.componentId).container;
  
    if (hasItemBarrier) {
      playerInventoryComponentContainer.setItem(hasItemBarrier.slot, new ItemStack("air"));
    }
    if (Amputate.isAmputated(player)) player.playAnimation("animation.player.amputation");
    //LoreManager.execute(player);
    Weight.execute(mainHand, player);
    LoreManager.applyLoreToInventory(player);
  }
}, 0);

world.afterEvents.entityHurt.subscribe(async event => {
  const { damageSource: playerEntity, hurtEntity, damage } = event;

  if (!playerEntity.damagingEntity) return;
  const equipment = playerEntity.damagingEntity?.getComponent(EntityEquippableComponent.componentId);
  const mainhand = equipment?.getEquipment(EquipmentSlot.Mainhand);

  if (!mainhand || !equipment) return;
  if (playerEntity.damagingEntity?.typeId != "minecraft:player") {
    Bleeding.execute(mainhand, hurtEntity);
    Amputate.add(mainhand, hurtEntity);
    Fracture.execute(hurtEntity, mainhand);
    BackStabbing.execute(mainhand, playerEntity.damagingEntity, hurtEntity)
    return;
  };
  Spear.execute({
      item: mainhand,
      player: playerEntity.damagingEntity,
      damage,
      attackedEntity: hurtEntity 
  });
  BackStabbing.execute(mainhand, playerEntity.damagingEntity, hurtEntity)
  Bleeding.execute(mainhand, hurtEntity);
  Weakness.execute(mainhand, playerEntity.damagingEntity);
  Sweep.execute(mainhand, playerEntity.damagingEntity);
  Contusion.execute(mainhand, hurtEntity);
  Fracture.execute(hurtEntity, mainhand);
  Amputate.add(mainhand, hurtEntity);
});

world.afterEvents.playerBreakBlock.subscribe(event => {
  const { player, block, itemStackAfterBreak } = event;
  
  HammerBreak.execute(itemStackAfterBreak, player, block);  
  ShovelBreak.execute(itemStackAfterBreak, player, block);
});

world.afterEvents.itemUseOn.subscribe(event => {
  const { itemStack, block, source } = event;
  
  if (source.typeId != "minecraft:player") return;
  HoeBreak.execute(itemStack, source, block);
});

system.run(() => new AntiBurner([ "netherite" ]));

system.beforeEvents.watchdogTerminate.subscribe(event => event.cancel = true);