import { world } from "mojang-minecraft";

let potions = [
  { id: 21, potion: "heal" },
  { id: 12, potion: "fireResistance" },
  { id: 19, potion: "waterBreathing" },
  { id: 14, potion: "moveSpeed" }
];
let splash_potions = [
  { id: 23, potion: "harm" },
  { id: 25, potion: "poison" },
  { id: 17, potion: "moveSlowdown" },
  { id: 34, potion: "weakness" }
];
let potion_duration = {};
let splash_potion_duration = {};

world.events.itemUse.subscribe(data => {
  const { item, source } = data;
  if (source.id == "minecraft:player" && source.getComponent("minecraft:variant").value == 47) {
    if (item.id == "minecraft:splash_potion" && item.getLore().includes("Morph Addon")) {
      const tick = () => {
        source.getComponent("minecraft:inventory").container.setItem(source.selectedSlot, item);
        splash_potion_duration[source.name] = 67;
        world.events.tick.unsubscribe(tick);
      };
      world.events.tick.subscribe(tick);
    };
  };
});

world.events.itemCompleteCharge.subscribe(data => {
  const { itemStack, source } = data;
  if (source.id == "minecraft:player" && source.getComponent("minecraft:variant").value == 47) {
    if (itemStack.id == "minecraft:potion" && itemStack.getLore().includes("Morph Addon")) {
      let glass_bottle = null;
      for (let slot = 0; slot < source.getComponent("minecraft:inventory").container.size; slot++) {
        let item = source.getComponent("minecraft:inventory").container.getItem(slot);
        if (item == null) { glass_bottle = slot; break; };
      };
      for (let slot = 0; slot < source.getComponent("minecraft:inventory").container.size; slot++) {
        let item = source.getComponent("minecraft:inventory").container.getItem(slot);
        if (item != null && item.id == "minecraft:glass_bottle") { glass_bottle = slot; break; };
      };
      const tick = () => {
        if (glass_bottle != null) {
          if (source.getComponent("minecraft:inventory").container.getItem(glass_bottle) != null) {
            source.runCommand(`replaceitem entity @s ${glass_bottle < 9 ? `slot.hotbar ${glass_bottle}` : `slot.inventory ${glass_bottle - 9}`} air`);
            source.getComponent("minecraft:inventory").container.setItem(source.selectedSlot, itemStack);
            potion_duration[source.name] = 67;
            world.events.tick.unsubscribe(tick);
          };
        } else {
          try {
            if (source.runCommand("testfor @s[m=c]")) {
              if (source.runCommand('testfor @e[type=item,c=1,x=~,y=~1.5,z=~,dx=0,dy=0,dz=0]')) {
                source.runCommand('kill @e[type=item,c=1,x=~,y=~1.5,z=~,dx=0,dy=0,dz=0]');
                potion_duration[source.name] = 67;
                world.events.tick.unsubscribe(tick);
              };
            };
          } catch {
            source.getComponent("minecraft:inventory").container.setItem(source.selectedSlot, itemStack);
            potion_duration[source.name] = 67;
            world.events.tick.unsubscribe(tick);
          };
        };
      };
      world.events.tick.subscribe(tick);
    };
  };
});

world.events.beforeItemUse.subscribe(data => {
  const { item, source } = data;
  if (source.id == "minecraft:player" && source.getComponent("minecraft:variant").value == 47) {
    if (item.id == "morph:unusable_potion" && item.getLore().includes("Morph Addon") && potion_duration[source.name] > 0) {
      source.runCommand(`tellraw @s {"rawtext":[{"text":"§7"},{"translate":"chat.mob_item.duration","with":["${Math.round((potion_duration[source.name] / 20) * 10) / 10}"]},{"text":"§r"}]}`);
    };
    if (item.id == "morph:unusable_splash_potion" && item.getLore().includes("Morph Addon") && splash_potion_duration[source.name] > 0) {
      source.runCommand(`tellraw @s {"rawtext":[{"text":"§7"},{"translate":"chat.mob_item.duration","with":["${Math.round((splash_potion_duration[source.name] / 20) * 10) / 10}"]},{"text":"§r"}]}`);
    };

    if (source.isSneaking && item.id == "minecraft:potion" && item.getLore().includes("Morph Addon")) {
      data.cancel = true;
      let next_item = source.getComponent("minecraft:inventory").container.getItem(source.selectedSlot);
      next_item.data = potions[potions.map(potion => potion.id).indexOf(item.data) == Object.keys(potions).length - 1 ? 0 : potions.map(potion => potion.id).indexOf(item.data) + 1].id;
      source.getComponent("minecraft:inventory").container.setItem(source.selectedSlot, next_item);
      source.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"Current: "},{"translate":"potion.${potions[potions.map(potion => potion.id).indexOf(next_item.data) - 1 == Object.keys(potions).length - 1 ? 0 : potions.map(potion => potion.id).indexOf(next_item.data)].potion}.name"},{"text":"\u005CnNext: "},{"translate":"potion.${potions[potions.map(potion => potion.id).indexOf(next_item.data) == Object.keys(potions).length - 1 ? 0 : potions.map(potion => potion.id).indexOf(next_item.data) + 1].potion}.name"}]}`);
    };
    if (source.isSneaking && item.id == "minecraft:splash_potion" && item.getLore().includes("Morph Addon")) {
      data.cancel = true;
      let next_item = source.getComponent("minecraft:inventory").container.getItem(source.selectedSlot);
      next_item.data = splash_potions[splash_potions.map(splash_potion => splash_potion.id).indexOf(item.data) == Object.keys(splash_potions).length - 1 ? 0 : splash_potions.map(splash_potion => splash_potion.id).indexOf(item.data) + 1].id;
      source.getComponent("minecraft:inventory").container.setItem(source.selectedSlot, next_item);
      source.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"Current: "},{"translate":"potion.${splash_potions[splash_potions.map(splash_potion => splash_potion.id).indexOf(next_item.data) - 1 == Object.keys(splash_potions).length - 1 ? 0 : splash_potions.map(splash_potion => splash_potion.id).indexOf(next_item.data)].potion}.splash.name"},{"text":"\u005CnNext: "},{"translate":"potion.${splash_potions[splash_potions.map(splash_potion => splash_potion.id).indexOf(next_item.data) == Object.keys(splash_potions).length - 1 ? 0 : splash_potions.map(splash_potion => splash_potion.id).indexOf(next_item.data) + 1].potion}.splash.name"}]}`);
    };
  };
});

world.events.tick.subscribe(data => {
  for (let player of Array.from(world.getPlayers())) {
    if (player.getComponent("minecraft:variant").value == 47) {
      if (!Object.keys(potion_duration).includes(player.name)) { potion_duration[player.name] = 0; };
      if (!Object.keys(splash_potion_duration).includes(player.name)) { splash_potion_duration[player.name] = 0; };

      if (potion_duration[player.name] > 0) {
        for (let slot = 0; slot < player.getComponent("minecraft:inventory").container.size; slot++) {
          let item = player.getComponent("minecraft:inventory").container.getItem(slot);
          try {
            if (item.id == "minecraft:potion" && item.getLore().includes("Morph Addon")) {
              let potion_id = item.data;
              player.runCommand(`replaceitem entity @s ${slot < 9 ? `slot.hotbar ${slot}` : `slot.inventory ${slot - 9}`} morph:unusable_potion 1 0 {"item_lock":{"mode": "lock_in_inventory"},"keep_on_death":{}}`);
              let morph_item = player.getComponent("minecraft:inventory").container.getItem(slot);
              morph_item.setLore([`§r§7Potion ID: ${potion_id}§r`,"Morph Addon"]);
              player.getComponent("minecraft:inventory").container.setItem(slot, morph_item);
            };
          } catch {};
        };
      };
      if (potion_duration[player.name] <= 0) {
        for (let slot = 0; slot < player.getComponent("minecraft:inventory").container.size; slot++) {
          let item = player.getComponent("minecraft:inventory").container.getItem(slot);
          try {
            if (item.id == "morph:unusable_potion" && item.getLore().includes("Morph Addon")) {
              let potion_id = item.getLore()[0].slice("§r§7Potion ID: ".length, item.getLore()[0].length - "§r".length);
              player.runCommand(`replaceitem entity @s ${slot < 9 ? `slot.hotbar ${slot}` : `slot.inventory ${slot - 9}`} minecraft:potion 1 ${potion_id} {"item_lock":{"mode": "lock_in_inventory"},"keep_on_death":{}}`);
              let morph_item = player.getComponent("minecraft:inventory").container.getItem(slot);
              morph_item.setLore(["Morph Addon"]);
              player.getComponent("minecraft:inventory").container.setItem(slot, morph_item);
            };
          } catch {};
        };
      };
      if (splash_potion_duration[player.name] > 0) {
        for (let slot = 0; slot < player.getComponent("minecraft:inventory").container.size; slot++) {
          let item = player.getComponent("minecraft:inventory").container.getItem(slot);
          try {
            if (item.id == "minecraft:splash_potion" && item.getLore().includes("Morph Addon")) {
              let potion_id = item.data;
              player.runCommand(`replaceitem entity @s ${slot < 9 ? `slot.hotbar ${slot}` : `slot.inventory ${slot - 9}`} morph:unusable_splash_potion 1 0 {"item_lock":{"mode": "lock_in_inventory"},"keep_on_death":{}}`);
              let morph_item = player.getComponent("minecraft:inventory").container.getItem(slot);
              morph_item.setLore([`§r§7Potion ID: ${potion_id}§r`,"Morph Addon"]);
              player.getComponent("minecraft:inventory").container.setItem(slot, morph_item);
            };
          } catch {};
        };
      };
      if (splash_potion_duration[player.name] <= 0) {
        for (let slot = 0; slot < player.getComponent("minecraft:inventory").container.size; slot++) {
          let item = player.getComponent("minecraft:inventory").container.getItem(slot);
          try {
            if (item.id == "morph:unusable_splash_potion" && item.getLore().includes("Morph Addon")) {
              let potion_id = item.getLore()[0].slice("§r§7Potion ID: ".length, item.getLore()[0].length - "§r".length);
              player.runCommand(`replaceitem entity @s ${slot < 9 ? `slot.hotbar ${slot}` : `slot.inventory ${slot - 9}`} minecraft:splash_potion 1 ${potion_id} {"item_lock":{"mode": "lock_in_inventory"},"keep_on_death":{}}`);
              let morph_item = player.getComponent("minecraft:inventory").container.getItem(slot);
              morph_item.setLore(["Morph Addon"]);
              player.getComponent("minecraft:inventory").container.setItem(slot, morph_item);
            };
          } catch {};
        };
      };
    };
    if (player.getComponent("minecraft:variant").value != 47) {
      if (Object.keys(potion_duration).includes(player.name)) { delete potion_duration[player.name]; };
      if (Object.keys(splash_potion_duration).includes(player.name)) { delete splash_potion_duration[player.name]; };
    };
  };
  for (let i = 0; i < Object.keys(potion_duration).length; i++) {
    if (potion_duration[Object.keys(potion_duration)[i]] > 0) {
      potion_duration[Object.keys(potion_duration)[i]] = potion_duration[Object.keys(potion_duration)[i]] - 1;
    };
  };
  for (let i = 0; i < Object.keys(splash_potion_duration).length; i++) {
    if (splash_potion_duration[Object.keys(splash_potion_duration)[i]] > 0) {
      splash_potion_duration[Object.keys(splash_potion_duration)[i]] = splash_potion_duration[Object.keys(splash_potion_duration)[i]] - 1;
    };
  };
});