import { Player, system, world } from "@minecraft/server";
import { arcaneRune } from "./arcane_rune.js";
import { inventory } from "./inventory.js";
import { lifeEssenceTick, lifeEssenceUse } from "./life_essence.js";
import { magneticWand } from "./magnetic_wand.js";
import "generator/guidebook.js";

world.afterEvents.playerJoin.subscribe(event => {
  system.runTimeout(() => playerJoin(event.playerName), 150);
});

function playerJoin(playerName) {
  const players = world.getPlayers({ name: playerName });
  if (players.length !== 1) return;

  const player = players[0];
  const firstJoin = player.getDynamicProperty("mythicus:generator.firstJoin") || false;
  if (firstJoin) return;

  player.setDynamicProperty("mythicus:generator.firstJoin", true);
};

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

system.runInterval(() => {
  dimension.runCommandAsync("function artifacts/amulet_of_attraction");
  dimension.runCommandAsync("function artifacts/skull");
}, 1);

system.runInterval(async () => {
  for (const player of world.getAllPlayers()) {
    try {
      await inventory(player);
      lifeEssenceTick(player);
    } catch {
      continue;
    }
  }
}, 5);

system.runInterval(() => {
  dimension.runCommandAsync("function artifacts/permanent_effects");
}, 10);

system.afterEvents.scriptEventReceive.subscribe(({ id, sourceEntity }) => {
  if (sourceEntity instanceof Player && id === "myth:life_essence") {
    lifeEssenceUse(sourceEntity);
  }
  if (sourceEntity instanceof Player && id === "myth:magnetic_wand") {
    magneticWand(sourceEntity);
  }
});

world.afterEvents.entityDie.subscribe(({ deadEntity }) => {
  if (!(deadEntity instanceof Player)) return;

  deadEntity.runCommandAsync("function artifacts/torch/remove");
  if (deadEntity.hasTag("arcane_rune")) {
    deadEntity.removeTag("arcane_rune");
    arcaneRune(deadEntity);
  }
});
