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

import { MSPlayer } from "../utils/player.js";
import { scheduleAmbient } from "./ambientAudio.js";

const INIT_INTERVAL = system.runInterval(() => {
  const players = world.getAllPlayers();
  if (players.length === 0) return;

  const player = players[0];
  if (player?.isValid() !== true || !player?.dimension) return;

  system.clearRun(INIT_INTERVAL);

  if (players.length !== 1) return;

  world.setDynamicProperty("mythicus_tw:hostPlayer.id", player.id);
  world.setDynamicProperty("mythicus_tw:hostPlayer.name", player.name);

  onWorldLoad(player);
}, 1);

world.afterEvents.playerJoin.subscribe(({ playerId, playerName }) => {
  const runIntervalId = system.runInterval(() => {
    const player = world.getPlayers({ name: playerName })[0];
    if (player?.isValid() !== true || !player?.dimension) return;

    onPlayerJoin(player);
    system.clearRun(runIntervalId);
  }, 1);
});

function onPlayerJoin(player) {
  const dim = player.dimension;
  const loc = player.location;

  if (player.getDynamicProperty("mythicus_tw:initJoin") !== true) {
    onPlayerInit(player, dim, loc);
  }

  MSPlayer.enableInputs(player);

  const fearAmount = player.getDynamicProperty("mythicus_tw:fear.amount") ?? 0;
  scheduleAmbient(player, fearAmount);

  const tipsId = player.getDynamicProperty("mythicus_tw:tipsId") ?? -1;
  if (tipsId !== (world.getDynamicProperty("mythicus_tw:playerTipsId") ?? 0)) {
    player.setDynamicProperty(
      "mythicus_tw:tipsId",
      world.getDynamicProperty("mythicus_tw:playerTipsId") ?? 0
    );
    player.setDynamicProperty("mythicus_tw:tipFlags", "".padStart(100, "0"));
  }
}

function onPlayerInit(player, dim, loc) {
  // set dynamic properties
  player.setDynamicProperty("mythicus_tw:initJoin", true);
  player.setDynamicProperty("mythicus_tw:tipFlags", "".padStart(100, "0"));
}

function onWorldLoad(player) {
  // initialize world if first load
  if (world.getDynamicProperty("mythicus_tw:worldInit") !== true) {
    onWorldInit(player);
  }

  const systemTime = Date.now();
  if (
    systemTime >
    (world.getDynamicProperty("mythicus_tw:systemTime") ?? 0) +
      7 * (24 * 60 * 60 * 1000)
  ) {
    const playerTipsId =
      world.getDynamicProperty("mythicus_tw:playerTipsId") ?? 0;
    world.setDynamicProperty("mythicus_tw:playerTipsId", playerTipsId + 1);
  }
  world.setDynamicProperty("mythicus_tw:systemTime", systemTime);
}

function onWorldInit(player) {
  // set dynamic properties
  world.setDynamicProperty("mythicus_tw:worldInit", true);
  world.setDynamicProperty("mythicus_tw:playerTipsId", 0);
  world.setDynamicProperty("mythicus_tw:watcherAggressionLevel", 0);

  // add objectives
  player.runCommand(
    'scoreboard objectives add "mythicus_edpt:watcher.collaborators" dummy'
  );

  // set gamerules
  //player.runCommand("gamerule sendcommandfeedback false");

  //debug.log("World initialized for inventory management.");
}
