import { world, system, TicksPerSecond, EntityDamageCause, EquipmentSlot, EntityComponentTypes } from "@minecraft/server";
import { damageItem } from "../misc/items";

// world.afterEvents.itemStartUse.subscribe(({ itemStack, source }) => {
//   if (itemStack.typeId === 'cyd_dino:spiked_shield') source.setDynamicProperty("cyd_dino:spiked_shield", true);
// });

// world.afterEvents.itemStopUse.subscribe(({ source, itemStack }) => {
//   if (itemStack.typeId === 'cyd_dino:spiked_shield') source.setDynamicProperty("cyd_dino:spiked_shield", false);
// });

// system.runInterval(() => {
//   for (const player of world.getPlayers()) {
//     if (player.getDynamicProperty("cyd_dino:spiked_shield")) {
//       player.addEffect("resistance", 3 * TicksPerSecond, { amplifier: 10, showParticles: false });
//     }
//   }
// });

world.afterEvents.entityHitEntity.subscribe((e) => {
  const { damagingEntity, hitEntity } = e;

  if (!damagingEntity || !hitEntity) return;
  if (!damagingEntity.isValid() || !hitEntity.isValid()) return;

  if (hitEntity.getDynamicProperty("cyd_dino:spiked_shield") || hitEntity.getProperty("cyd_dino:shield_blocking")) {
    damagingEntity.applyDamage(4, { cause: EntityDamageCause.entityAttack, damagingEntity: damagingEntity });
    const direction = {
      x: damagingEntity.location.x - hitEntity.location.x, y: 0.1, z: damagingEntity.location.z - hitEntity.location.z
    }
    damagingEntity.applyKnockback(direction.x, direction.z, 0.8, 0.4);
    damageItem(hitEntity, EquipmentSlot.Mainhand, 1);
    hitEntity.dimension.playSound("item.shield.block", hitEntity.location, { volume: 1.0, pitch: 1.0 });
  }
});

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const equippable = player.getComponent(EntityComponentTypes.Equippable);
    const item = equippable.getEquipment(EquipmentSlot.Mainhand);
    const item2 = equippable.getEquipment(EquipmentSlot.Offhand);

    if (item?.typeId === 'cyd_dino:spiked_shield' || item2?.typeId === 'cyd_dino:spiked_shield') {
      if (player.isSneaking) {
        player.setDynamicProperty("cyd_dino:spiked_shield", true);
        player.addEffect("resistance", 1 * TicksPerSecond, { amplifier: 10, showParticles: false });
      }
      else {
        player.setDynamicProperty("cyd_dino:spiked_shield", false);
      }
    } else {
      player.setDynamicProperty("cyd_dino:spiked_shield", false);
    }
  }
}, 1)
