import { Entity, EntityTypeFamilyComponent, Player, system, world } from "@minecraft/server";
import { Helper } from "../utils/Helper";
const ENTITY_ID = "sf_nba:stinky_balloon";
const EFFECTS_DURATION = { poison: 10, nause: 5, aoe: 10 };
const IS_POPPED_PROPERTY = "sf_nba:is_popped";
const PROJECTILE_STRENGTH = 1.3;
export class StinkyBalloon {
  constructor() {
    this.onUse = this.onUse.bind(this);
    system.run(() => {
      this.#onHitBlockOrEntity();
    });
  }
  onUse({ source: player }) {
    const { dimension, location: pos } = player;
    Helper.decreaseMainhandItemStack(player);
    dimension.playSound("mob.snowgolem.shoot", pos, { pitch: 0.8 });
    const headPos = player.getHeadLocation();
    const rotation = player.getViewDirection();
    const projectile = player.dimension.spawnEntity(ENTITY_ID, {
      x: headPos.x - rotation.z * 0.3 + rotation.x * 0.2,
      y: headPos.y,
      z: headPos.z + rotation.x * 0.3 + rotation.z * 0.2,
    });
    projectile.setRotation(player.getRotation());
    projectile.clearVelocity();
    projectile.applyImpulse({
      x: rotation.x * PROJECTILE_STRENGTH + player.getVelocity().x,
      y: rotation.y * 1.25,
      z: rotation.z * PROJECTILE_STRENGTH + player.getVelocity().z
    });
  }
  #onHitBlockOrEntity() {
    const func = (projectile) => {
      if (projectile.typeId !== ENTITY_ID) return;
      this.#addOnHitAnythingEffects(projectile);
    };
    world.afterEvents.projectileHitBlock.subscribe(({ projectile }) => func(projectile));
    world.afterEvents.projectileHitEntity.subscribe(({ projectile }) => func(projectile));
  }
  #addOnHitAnythingEffects(projectile) {
    if (!projectile.isValid()) return;
    if (projectile.getProperty(IS_POPPED_PROPERTY)) return;
    const { dimension, location } = projectile;
    const pos = { ...location, y: location.y + 1 };
    dimension.spawnParticle("sf_nba:stinky_balloon_pop", pos);
    dimension.playSound("sf_nba.stinky_balloon.pop", pos);
    dimension.playSound("sf_nba.skunk.spray", pos);
    projectile.setProperty(IS_POPPED_PROPERTY, true);
    this.#spawnAOE(projectile);
  }
  #spawnAOE(projectile) {
    if (!projectile.isValid()) return;
    let i = 0;
    const _id = system.runInterval(() => {
      if (!projectile.isValid()) {
        system.clearRun(_id);
        return;
      }
      const { dimension, location } = projectile;
      const entities = dimension.getEntities({
        location,
        maxDistance: 3,
        excludeFamilies: ["sf_nba:projectile"]
      });
      for (const entity of entities) {
        entity.addEffect("poison", 20 * EFFECTS_DURATION.poison);
        if (entity instanceof Player) {
          entity.addEffect("nausea", 20 * EFFECTS_DURATION.nause);
        }
      }
      i += 0.25;
      if (i >= EFFECTS_DURATION.aoe) {
        projectile.remove();
        system.clearRun(_id);
      }
    }, 5);
  }
}
new StinkyBalloon();