/*
hello dear add-on maker. want to use my code? sure. but it would probably help if you understand how it works instead of
just copy pasting it and changing ids...

the code shouldnt be too hard to understand. should be easy to configure for your own things

but if you're mostly just using the same code, would be nice if you credit

otherwise, have fun removing hit immunity :)

note that this version of my hit immunity removal code is edited quite abit for this add-on and does not have gun durability

- JuliusScizzor
*/

import {
  GameMode,
  world,
  Vector,
  Player,
  system,
  EntityDamageCause,
  EntityEquipmentInventoryComponent,
  EquipmentSlot,
  ItemStack,
  ItemEnchantsComponent,
  EnchantmentTypes,
  ItemDurabilityComponent,
  EntityHealthComponent,
  Entity,
} from "@minecraft/server";

import './functions';
import './customProjectileDamage';

world.afterEvents.playerSpawn.subscribe((event) => {
	if (!(event.initialSpawn)) return
    system.runTimeout(() => {
      event.player.runCommand(`tellraw @s {"rawtext":[{"translate":"system.join"}]}`)
    },120)
})

world.beforeEvents.chatSend.subscribe((ev) => {
  let { sender, message } = ev;

  if (!message.startsWith('!')) return;

  ev.cancel = true;
  const command = message.substring(1);

  if (command in commands) {
    const { command: commandToRun, notification, requiresOp } = commands[command];
    
    if (requiresOp && !sender.isOp()) {
      sender.sendMessage(`§cYou don't have permission to use this command. Type !list for a list of commands.`);
    } else {
      sender.runCommandAsync(commandToRun);
    }
  } else {
    sender.sendMessage(`§c${command} is not a valid command. Type !list for a list of commands.`);
  }
});

const commands = {
  "fix": {
    command: "execute as @a[tag=Host] at @s run function Console.fix",
    requiresOp: true, 
  },
  "skip": {
    command: "scoreboard players set @a[tag=Host] start_timer 1",
    requiresOp: true, 
  },
  "readyall": {
    command: "execute as @a[tag=Host] at @s run function game/player/force_ready",
    requiresOp: true, 
  },
  "unreadyall": {
    command: "execute as @a[tag=Host] at @s run function game/player/force_unready",
    requiresOp: true, 
  },
  "ready": {
    command: "function game/player/ready",
    requiresOp: false, 
  },
  "unready": {
    command: "function game/player/unready",
    requiresOp: false, 
  },
  "leave": {
    command: "execute as @s[m=spectator] run function game/spectate/return",
    requiresOp: false, 
  },
  "chuuuck": {
    command: "playsound chuck.chuuuck @a ~~~",
    requiresOp: false, 
  },
  "list": {
    command: "function cmd/list",
    requiresOp: false, 
  },
};



function playerSystem(player) {
}

system.run(function playerTick(ev) {
  system.run(playerTick); 
  for (let plr of world.getPlayers()) {
    playerSystem(plr);
  }

  for (let ent of world.getDimension("overworld").getEntities()) {
  }
})

system.afterEvents.scriptEventReceive.subscribe(event => {
  const entity = event.sourceEntity
  if (event.id == "js:hp_pickup") {
    healthPowerup(entity);
  }
})


function setSlotToAir(player, slot) {
  if (slot < 9) {
    player.runCommandAsync(`replaceitem entity @s slot.hotbar ${slot} air`);
  } else player.runCommandAsync(`replaceitem entity @s slot.inventory ${slot - 9} air`);
}

function itemQuery(player, itemIds) {
  const comp = player.getComponent("inventory");
  const inv = comp.container;
  let amount = 0;
  let info = [];
  for (let i = 0; i < inv.size; i++) {
    const item = inv.getItem(i);
    if (!item) continue;

    const { typeId, amount: iAmount, data } = item;
    if (itemIds.includes(typeId.replace("minecraft:", ""))) {
      amount += iAmount;
      info.push({
        slot: i,
        item: { typeId, amount: iAmount, data },
      });
    }
  }
  return {
    amount,
    slots: info,
  };
}

function healthPowerup(player) {
  const hp = player.getComponent("health");
  if (hp.currentValue <= 0) return;
  const itemInfo = itemQuery(player, ["js:health"]);
  if (itemInfo.amount <= 0) return;
  for (let slot of itemInfo.slots) setSlotToAir(player, slot.slot);

  hp.setCurrentValue(hp.currentValue + (itemInfo.amount * 2));
  player.playSound("misc.hp_pickup");
} 

system.runInterval(() => {
  world.getDimension("overworld").runCommandAsync(`function 1s_timer`)
 },20)