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

function getScore(player, objective) {
  try {
    const s = world.scoreboard.getObjective(objective);
    if (!s) world.scoreboard.addObjective(objective, objective);
    return s.getScore(player.scoreboardIdentity);
  } catch {
    return 0;
  }
 }
system.runInterval(() => {

  for (const player of world.getPlayers()){
    if (player.hasTag("fly")) {
      player.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, Math.sqrt(Math.abs(player.getViewDirection().x)*1.1 + Math.abs(player.getViewDirection().z)*1.1 )*0.2, 0.2)
    }
  }
 }
)
system.runInterval(() => {
  const blood_moon = (((world.getAbsoluteTime() - world.getTimeOfDay())/24000)+2) % 8 == 0;
  const night_time = world.getTimeOfDay() > 13000 && world.getTimeOfDay() < 23000;
  if (blood_moon && night_time) {
    for (const player of world.getPlayers()){
      player.runCommand(`tag @s add blood_moon`);
    }
  }
  if (!blood_moon || !night_time) {
    for (const player of world.getPlayers()){
      player.runCommand(`tag @s remove blood_moon`);
    }
  }
  const entities = world.getDimension("minecraft:overworld").getEntities({excludeFamilies: ["projectile", "inanimate"] });
  for (const entity of entities){
    if (entity.hasTag("bleeding1")) {
      entity.removeTag("bleeding1");
      entity.runCommand(`damage @s 1 none`)
      entity.runCommand(`particle edx:blood ~~~`);
    }
    if (entity.hasTag("bleeding2")) {
      entity.removeTag("bleeding2");
      entity.runCommand(`tag @s add bleeding1`);
      entity.runCommand(`damage @s 1 none`)
      entity.runCommand(`particle edx:blood ~~~`);
    }
    if (entity.hasTag("bleeding3")) {
      entity.removeTag("bleeding3");
      entity.runCommand(`tag @s add bleeding2`);
      entity.runCommand(`damage @s 1 none`)
      entity.runCommand(`particle edx:blood ~~~`);
    }
    if (entity.hasTag("bleeding4")) {
      entity.removeTag("bleeding4");
      entity.runCommand(`tag @s add bleeding3`);
      entity.runCommand(`damage @s 2 none`)
      entity.runCommand(`particle edx:blood ~~~`);
    }
    if (entity.hasTag("bleeding")) {
      entity.removeTag("bleeding");
      entity.runCommand(`tag @s add bleeding4`);
      entity.runCommand(`damage @s 2 none`)
      entity.runCommand(`particle edx:blood ~~~`);
    }
  }


  for (const player of world.getPlayers()){
  if (player.hasTag("undying_flower") && player.hasTag("day")) {
    let health = player.getComponent("health")
    health.setCurrentValue(health.currentValue+0.33)
  }
  if (player.hasTag("fur_chestplate") && player.hasTag("frozen")) {
    let health = player.getComponent("health")
    health.setCurrentValue(health.currentValue+0.20)
  }
}
  },20)