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

world.beforeEvents.worldInitialize.subscribe((eventData) => {
  eventData.blockComponentRegistry.registerCustomComponent(
    "pb_plane:fuel_tank_data",
    {
      beforeOnPlayerPlace(event) {
        try {
          const { player, block } = event;
          const fuelQtyLore = player
            .getComponent("equippable")
            .getEquipment("Mainhand")
            .getLore();
          const fuelLine = fuelQtyLore[0];
          const fuelQty = parseInt(fuelLine.split(" ")[2].split("/")[0]);
          if (fuelQty != undefined) {
            system.runTimeout(() => {
              block.setPermutation(
                block.permutation.withState("pb_plane:fuel_quantity", fuelQty)
              );
            });
          }
        } catch (error) {}
      },
    }
  );
});

world.beforeEvents.playerBreakBlock.subscribe((event) => {
  const { block } = event;
  if (block.typeId != "pb_plane:fuel_tank") return;
  let { x, y, z } = block.location;
  (y += 0.5), (x += 0.5), (z += 0.5);
  const fuelQty = block.permutation.getState("pb_plane:fuel_quantity");
  const fuelTankItem = new ItemStack(`pb_plane:fuel_tank`, 1);

  system.run(() => {
    fuelTankItem.setLore([`Stored Fuel: ${fuelQty}/8`]);
    block.dimension.spawnItem(fuelTankItem, { x, y, z });
  });
});
