import { world, system, MolangVariableMap } from "@minecraft/server";
import { get_PlayerGroups, CurrentEventProp } from "./utilities";
import { ShadowSpawnSystem } from "./shadow";

const eventId = "solar_eclipse";

let ShadowSpawnRunId;

const listOfAngryMobs = [
  "minecraft:pig",
  "minecraft:sheep",
  "minecraft:chicken",
  "minecraft:cow",
];
export function solar_eclipse_MAIN(dimension) {
  system.runInterval(() => {
    const event = CurrentEventProp.getProp();

    if (!(event.id == eventId && event.status == "is_happening")) {
      get_PlayerGroups(dimension, 12).forEach((group) => {
        dimension
          .getEntities({
            families: ["solar_eclipse"],
            closest: 5,
            location: {
              x: group.location.x,
              y: dimension.getTopmostBlock({
                x: group.location.x,
                z: group.location.z,
              }).location.y,
              z: group.location.z,
            },
            maxDistance: 12,
          })
          .forEach(mobsNotAngry);
      });
      return;
    }
    if (event.timer >= 0) {
      get_PlayerGroups(dimension, 25).forEach((group) => {
        visualEffects(group);
      });
      get_PlayerGroups(dimension, 110).forEach((group) => {
        placeSun(group.location);
      });
      get_PlayerGroups(dimension, 12).forEach((group) => {
        dimension
          .getEntities({
            families: ["mob"],
            closest: 5,
            location: {
              x: group.location.x,
              y: dimension.getTopmostBlock({
                x: group.location.x,
                z: group.location.z,
              }).location.y,
              z: group.location.z,
            },
            maxDistance: 12,
          })
          .forEach(transformMobs);
      });
      if (event.timer < event.maxDuration) {
        if (event.timer == 1) {
          world.sendMessage([
            {
              translate: `tvf_randev.event.start.${event.id}`,
            },
          ]);
        }
        event.timer += 1;
      }
      if (ShadowSpawnRunId == undefined) {
        ShadowSpawnRunId = ShadowSpawnSystem(dimension, 0.5, 1200);
      }
    }
    if (
      event.forcedEnd == true ||
      (event.timer >= event.maxDuration &&
        (world.getTimeOfDay() > 13000 || world.getTimeOfDay() < 1001))
    ) {
      if (ShadowSpawnRunId != undefined) {
        system.clearRun(ShadowSpawnRunId);
        ShadowSpawnRunId = undefined;
      }
      event.status = "is_end";
      system.runTimeout(() => {
        dimension.runCommand("/fog @a remove tvf_randev:fogsID");
      }, 20 * 10);
      // world.sendMessage([{ translate: `tvf_randev.event.end.${event}` }])
    }
    CurrentEventProp.update(event);
  });
  function placeSun(location) {
    if (system.currentTick % 100 == 0) {
      if (world.getTimeOfDay() < 13000) {
        let map = new MolangVariableMap();
        let daytime = world.getTimeOfDay();
        map.setFloat("daytime", daytime);
        map.setFloat("period", 15000);
        dimension.spawnParticle("tvf_randev:solar_eclipse_sun", location, map);
      }
    }
  }
  function visualEffects(group) {
    if (system.currentTick % 20 == 0) return;

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

    dimension.spawnParticle("tvf_randev:solar_eclipse_sky", group.location);
  }
  function transformMobs(sourceMob) {
    if (system.currentTick % 100 != 0) return;
    if (!listOfAngryMobs.includes(sourceMob.typeId)) return;
    const newMobId =
      sourceMob.typeId.replace(/minecraft:/g, "tvf_randev:") + "_angry";
    const rot = sourceMob.getRotation();
    const isBaby = sourceMob.getComponent("minecraft:is_baby");
    const sourceLoc = sourceMob.location;
    const climateVar = sourceMob.getProperty("minecraft:climate_variant");
    let newMob = dimension.spawnEntity(newMobId, sourceLoc);
    if (newMobId == "tvf_randev:sheep_angry") {
      const color = sourceMob.getComponent("minecraft:color").value;
      newMob.triggerEvent(`tvf_randev:color_${color}`);
    }
    if (climateVar) {
      newMob.setProperty("minecraft:climate_variant", climateVar);
    }
    if (isBaby != undefined) {
      newMob.triggerEvent("minecraft:entity_born");
    }
    newMob.setRotation(rot);
    sourceMob.remove();
  }
  function mobsNotAngry(sourceMob) {
    if (system.currentTick % 200 != 0) return;
    const newMobId = sourceMob.typeId
      .replace("tvf_randev", "minecraft")
      .replace("_angry", "");
    if (!listOfAngryMobs.includes(newMobId)) return;
    const rot = sourceMob.getRotation();
    const isBaby = sourceMob.getComponent("minecraft:is_baby");
    const sourceLoc = sourceMob.location;
    const climateVar = sourceMob.getProperty("minecraft:climate_variant");
    let newMob = dimension.spawnEntity(newMobId, sourceLoc);
    if (climateVar) {
      newMob.setProperty("minecraft:climate_variant", climateVar);
    }
    if (isBaby != undefined) {
      newMob.triggerEvent("minecraft:entity_born");
    }
    newMob.setRotation(rot);
    sourceMob.remove();
  }
}
