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

function useFuel(vehicle) {
  const inv = vehicle.getComponent("inventory")?.container;
  const equip = inv?.getItem(0);
  if (!equip) return;
  if (equip.typeId != "pb_plane:biofuel_can_full") return;
  const fuelQty = equip.getComponent("durability").damage;
  const maxFuel = equip.getComponent("durability").maxDurability;
  const driver = vehicle?.getComponent("rideable").getRiders()[0];

  if (fuelQty == (maxFuel / 10) * 7) {
    driver.runCommandAsync(
      `titleraw @s title {"rawtext":[{"translate":"action.hint.pb_plane:low_fuel_70"}]}`
    );
  }
  if (fuelQty == (maxFuel / 10) * 8) {
    driver.runCommandAsync(
      `titleraw @s title {"rawtext":[{"translate":"action.hint.pb_plane:low_fuel_80"}]}`
    );
  }
  if (fuelQty == (maxFuel / 10) * 9) {
    driver.runCommandAsync(
      `titleraw @s title {"rawtext":[{"translate":"action.hint.pb_plane:low_fuel_90"}]}`
    );
  }
  if (fuelQty != maxFuel) {
    vehicle.runCommandAsync(
      `replaceitem entity @s slot.inventory 0 pb_plane:biofuel_can_full 1 ${
        fuelQty + 1
      }`
    );
  }
  if (fuelQty >= maxFuel) {
    vehicle.runCommandAsync(
      `replaceitem entity @s slot.inventory 0 pb_plane:biofuel_can_empty`
    );
    driver.runCommandAsync(
      `titleraw @s title {"rawtext":[{"translate":"action.hint.pb_plane:empty_fuel"}]}`
    );
  }
}

system.runInterval(() => {
  let entities = world
    .getDimension("overworld")
    .getEntities({ families: ["pb_plane"] });
  entities = entities.concat(
    world.getDimension("nether").getEntities({ families: ["pb_plane"] })
  );
  entities = entities.concat(
    world.getDimension("the_end").getEntities({ families: ["pb_plane"] })
  );

  entities.forEach((vehicle) => {
    const isRideable = vehicle.getComponent("rideable");

    if (!isRideable) return;

    const riders = vehicle.getComponent("rideable").getRiders().length;
    const driver = vehicle.getComponent("rideable").getRiders()[0];
    const velocity = vehicle.getVelocity();
    // Check if the vehicle has a driver and is moving
    if (riders > 0 && driver) {
      if (
        (vehicle.matches({ families: ["pb_plane_plane"] }) ||
          vehicle.matches({ families: ["pb_plane_car"] }) ||
          vehicle.matches({ families: ["pb_plane_boat"] })) &&
        (velocity.x != 0 || velocity.z != 0 || velocity.y != 0)
      ) {
        useFuel(vehicle);
      }
      if (
        (vehicle.matches({ families: ["pb_plane_helicopter"] }) ||
          vehicle.matches({ families: ["pb_plane_drone"] }) ||
          vehicle.matches({ families: ["pb_plane_blimp"] })) &&
        !vehicle.isOnGround
      ) {
        useFuel(vehicle);
      }
    }
  });
}, 40);
