import { system, world } from "@minecraft/server";

const overworld = world.getDimension("overworld");

const traders = [
  "mythicus_ws:waystone.trader",
];

system.runInterval(() => {
  spawnTrader();
  despawnTrader();
}, 20);

async function spawnTrader() {
  let countdown = world.getDynamicProperty("mythicus_ws:trader_countdown");
  if (typeof countdown !== "number") {
    // 5 seconds
    countdown = 60 * 20;
  }
  if (countdown > 0) {
    countdown--;
    world.setDynamicProperty("mythicus_ws:trader_countdown", countdown);
    return;
  }
  world.setDynamicProperty("mythicus_ws:trader_countdown");

  let spawnChance = world.getDynamicProperty("mythicus_ws:trader_spawn_chance");
  if (typeof spawnChance !== "number") {
    spawnChance = 0.25;
  }
  if (Math.random() > spawnChance) {
    spawnChance = Math.min(0.75, spawnChance + 0.25);
    world.setDynamicProperty("mythicus_ws:trader_spawn_chance", spawnChance);
    return;
  }
  world.setDynamicProperty("mythicus_ws:trader_spawn_chance");

  const playerList = overworld.getPlayers();
  const player = playerList[Math.floor(Math.random() * playerList.length)];
  let { x, y, z } = player.location;
  x = Math.floor(x);
  y = 320;
  z = Math.floor(z);

  const identifier = traders[Math.floor(Math.random() * traders.length)];
  const trader = overworld.spawnEntity(identifier, { x, y, z });
  await trader.runCommandAsync(`spreadplayers ${x} ${z} 0 48 @s`);
  trader.triggerEvent("mythicus_ws:wolves.2");
}

function despawnTrader() {
  for (const trader of overworld.getEntities({ families: ["mythicus_merchant"] })) {
    let age = trader.getDynamicProperty("mythicus_ws:age");
    if (typeof age !== "number") {
      age = 0;
    }
    // Despawn after 40 minutes
    if (age < 60 * 40) {
      age++;
      trader.setDynamicProperty("mythicus_ws:age", age);
      continue;
    }
    // Prevent despawn when near players
    const players = overworld.getEntities({ type: "minecraft:player", location: trader.location, maxDistance: 6 });
    if (players.length > 0) {
      continue;
    }
    trader.remove();
  }
}