import { world, system } from "@minecraft/server";
import { randomOneOrMinusOne } from "./time_events";
import { get_PlayerGroups, CurrentEventProp } from "./utilities";

const eventId = "sticky_rain";
export function sticky_rain_MAIN(dimension) {
  system.runInterval(() => {
    const event = CurrentEventProp.getProp();
    if (!(event.id == eventId && event.status == "is_happening")) return;
    if (event.timer < event.maxDuration) {
      if (event.timer == 1) {
        world.sendMessage([
          {
            translate: `tvf_randev.event.start.${event.id}`,
          },
        ]);
      }
      get_PlayerGroups(dimension, 25).forEach((group) => {
        visualEffects(dimension, group);
      });
      get_PlayerGroups(dimension, 12).forEach((group) => {
        summonSlime(dimension, group.location);
      });
      event.timer += 1;
    }
    if (event.forcedEnd == true || event.timer >= event.maxDuration) {
      event.status = "is_end";
      system.runTimeout(() => {
        dimension.runCommand("/fog @a remove tvf_randev:fogsID");
      }, 20 * 10);
      world.sendMessage([
        {
          translate: `tvf_randev.event.end.${event.id}`,
        },
      ]);
    }
    CurrentEventProp.update(event);
  });
}
function visualEffects(dimension, group) {
  if (system.currentTick % 20 != 0) return;

  group.players.forEach((player) => {
    if (player.graphicsMode == "Deferred") {
      player.runCommand(
        "/fog @s push tvf_randev:sticky_rain_vol tvf_randev:fogsID"
      );
    } else {
      player.runCommand(
        "/fog @s push tvf_randev:sticky_rain_fog tvf_randev:fogsID"
      );
    }
  });

  dimension.spawnParticle("tvf_randev:sticky_rain_sky", group.location);
}
function summonSlime(dimension, location) {
  if (system.currentTick % 20 != 0) return;
  let spawnLocation = {
    x:
      location.x + randomOneOrMinusOne() * (5 + Math.floor(Math.random() * 10)),
    y: location.y,
    z:
      location.z + randomOneOrMinusOne() * (5 + Math.floor(Math.random() * 10)),
  };
  spawnLocation.y =
    dimension.getTopmostBlock({
      x: spawnLocation.x,
      z: spawnLocation.z,
    }).location.y + 20;
  let mob;

  mob = dimension.spawnEntity("tvf_randev:colored_slime", spawnLocation);
  mob.setProperty("property:color", Math.floor(Math.random() * 16));
  //else mob = dimension.spawnEntity('minecraft:slime', spawnLocation)
  mob.addEffect("slow_falling", 20 * 10, {
    showParticles: false,
  });
}
