import * as mc from "@minecraft/server";

import * as selectors from "../utils/selectors";
import * as vector from "../utils/vector";

import { ATTACK_RANGE } from "./bluff";

const SPEED = 0.3;

export function tick1(entity) {
  if (entity.hasTag("hf_mzs_finished")) return;
  if (entity.getDynamicProperty("hf_mzs:dist") === undefined) entity.setDynamicProperty("hf_mzs:dist", 0);
  if (entity.getDynamicProperty("hf_mzs:dist") >= ATTACK_RANGE) {
    finish(entity, entity.location);
    return;
  }
  const entities = selectors.union(
    {
      location: {
        x: entity.location.x,
        y: entity.location.y,
        z: entity.location.z,
      },
      maxDistance: 1,
      excludeFamilies: ["inanimate", "hf_mzs_bluff"],
    },
    ["player", "mob"],
    entity.dimension,
    entity.id
  );
  for (let element of entities) {
    if (!element.isValid()) return;
    const ground = element.dimension.getBlockFromRay(vector.add(element.location, vector.up), vector.down, {
      maxDistance: 2,
      includeLiquidBlocks: false,
      includePassableBlocks: false,
    });
    if (ground === undefined) return;
    const pos = {
      x: Math.floor(element.location.x) + 0.5,
      y: ground.block.location.y + 1,
      z: Math.floor(element.location.z) + 0.5,
    };
    finish(entity, pos);
    return;
  }

  let dir;
  if (entity.getDynamicProperty("hf_mzs:x_dir") !== undefined)
    dir = {
      x: entity.getDynamicProperty("hf_mzs:x_dir") * SPEED,
      y: 1.5,
      z: entity.getDynamicProperty("hf_mzs:z_dir") * SPEED,
    };
  else dir = vector.add(vector.multiply(vector.forward, SPEED), vector.up);

  const block = entity.dimension.getBlockFromRay(vector.add(entity.location, dir), vector.down, {
    maxDistance: 3.5,
    includeLiquidBlocks: false,
    includePassableBlocks: false,
  });
  if (block === undefined) {
    entity.remove();
    return;
  }
  entity.teleport(vector.add(block.block.location, block.faceLocation));
  entity.runCommand("/particle hf_mzs:bluff_projectile2 ~~~");
  entity.setDynamicProperty("hf_mzs:dist", entity.getDynamicProperty("hf_mzs:dist") + SPEED);
}

export function finish(entity, location) {
  if (!entity.isValid()) {
    entity.remove();
    return;
  }
  const boulder = entity.dimension.spawnEntity("hf_mzs:bluff_boulder", location);
  boulder.setDynamicProperty("hf_mzs:x_dir", entity.getDynamicProperty("hf_mzs:x_dir"));
  boulder.setDynamicProperty("hf_mzs:z_dir", entity.getDynamicProperty("hf_mzs:z_dir"));
  boulder.setDynamicProperty("hf_mzs:shooter", entity.getDynamicProperty("hf_mzs:shooter"));
  entity.addTag("hf_mzs_finished");
  entity.runCommand("/tp @s ~~-5~");
}
