import { world, Player } from "@minecraft/server";
import Vector from "../Vector";
const bulletDamage = {
  bullet1: {
    damageBase: 22,
    damageMin: 8,
    fallOffMin: 8,
    fallOffMax: 20,
  },
  bullet2: {
    damageBase: 10,
    damageMin: 7,
    fallOffMin: 48,
    fallOffMax: 96,
  },
  bullet3: {
    damageBase: 18,
    damageMin: 13,
    fallOffMin: 56,
    fallOffMax: 128,
  },
  bullet4: {
    damageBase: 10,
    damageMin: 6,
    fallOffMin: 32,
    fallOffMax: 56,
  },
  bullet5: {
    damageBase: 16,
    damageMin: 11,
    fallOffMin: 56,
    fallOffMax: 128,
  },
  bullet6: {
    damageBase: 20,
    damageMin: 13,
    fallOffMin: 32,
    fallOffMax: 128,
  },
  bullet7: {
    damageBase: 22,
    damageMin: 10,
    fallOffMin: 32,
    fallOffMax: 88,
  },
  bullet8: {
    damageBase: 18,
    damageMin: 13,
    fallOffMin: 56,
    fallOffMax: 128,
  },
  bullet9: {
    damageBase: 20,
    damageMin: 14,
    fallOffMin: 56,
    fallOffMax: 128,
  },
  bullet10: {
    damageBase: 12,
    damageMin: 9,
    fallOffMin: 48,
    fallOffMax: 96,
  },
  bullet11: {
    damageBase: 22,
    damageMin: 11,
    fallOffMin: 64,
    fallOffMax: 128,
  },
  bullet12: {
    damageBase: 19,
    damageMin: 14,
    fallOffMin: 64,
    fallOffMax: 128,
  },
  bullet13: {
    damageBase: 16,
    damageMin: 11,
    fallOffMin: 64,
    fallOffMax: 128,
  },
  bullet14: {
    damageBase: 11,
    damageMin: 6,
    fallOffMin: 32,
    fallOffMax: 96,
  },
  bullet15: {
    damageBase: 18,
    damageMin: 9,
    fallOffMin: 64,
    fallOffMax: 128,
  },
};

world.afterEvents.projectileHitEntity.subscribe((ev) => {
  const src = ev.source;
  if (!(src instanceof Player)) return;
  const proj = ev.projectile;
  try {
    if (proj.typeId != "ra:bullet.projectile") return;
  } catch {
    return;
  }
  const entityHit = ev.getEntityHit();
  if (!entityHit) return;
  const entity = entityHit.entity;
  if (!entity?.isValid()) return;

  const variant = proj.getComponent("mark_variant")?.value ?? 0;
  if (variant == 0) return;

  const damageDef = bulletDamage[`bullet${variant}`];
  if (!damageDef) {
    console.warn(`Could not find a bullet damage definition for variant ${variant}`);
    return;
  }

  const dist = Vector.length(Vector.subtract(src.location, ev.location));
  let dmg = damageDef.damageBase;
  if (dist > damageDef.fallOffMin) {
    const fallOff = Math.max(1 - (dist - damageDef.fallOffMin) / (damageDef.fallOffMax - damageDef.fallOffMin), 0);
    dmg = Math.round(Math.max(dmg * fallOff, damageDef.damageMin));
  }
  entity.applyDamage(dmg, { damagingProjectile: proj, damagingEntity: src });

  if (entity === Player) return;
  const vel = entity.getVelocity();
  entity.clearVelocity();
  entity.applyImpulse(vel);
});
