import { system, world, ItemStack, EntityComponentTypes } from "@minecraft/server";
import "./items.js";
import "./fetching.js";
import "./blocks.js";

world.afterEvents.playerJoin.subscribe((e) => {
  const interval = system.runInterval(() => {

    // Find player
    const player = world.getAllPlayers().find((val) => val.id === e.playerId);

    // Check if player is valid
    if (player?.isValid) {

      // Check if player has joined before
      if (!player.getDynamicProperty("oct_dogs:joined")) {
        player.setDynamicProperty("oct_dogs:joined", true);

        // Give guidebook
        if (player.getComponent(EntityComponentTypes.Inventory).container.emptySlotsCount === 0) {
          try { player.dimension.spawnItem(new ItemStack("oct_dogs:guidebook", 1), player.location); } catch (e) { }
        } else {
          player.getComponent(EntityComponentTypes.Inventory).container.addItem(new ItemStack("oct_dogs:guidebook", 1));
        }
      }

      // Clear interval
      system.clearRun(interval);
    }

  });

});