// priority: 995

const $FTBRanksAPI = Java.loadClass("dev.ftb.mods.ftbranks.api.FTBRanksAPI");
const $NumberPermissionValue = Java.loadClass(
  "dev.ftb.mods.ftbranks.impl.permission.NumberPermissionValue"
);

ServerEvents.loaded((event) => {
  event.server.scheduleInTicks(100, (_) => {
    updateRanks();
    //console.log("WINNER WINNER CHICKEN DINNER");
  });
});

const ranks = [
  {
    name: "ultimine_upgrade0",
    power: 1,
    permissions: {
      "ftbultimine.max_blocks": 16,
    },
  },
  {
    name: "ultimine_upgrade1",
    power: 2,
    permissions: {
      "ftbultimine.max_blocks": 32,
    },
  },
  {
    name: "ultimine_upgrade2",
    power: 3,
    permissions: {
      "ftbultimine.max_blocks": 48,
    },
  },
  {
    name: "ultimine_upgrade3",
    power: 4,
    permissions: {
      "ftbultimine.max_blocks": 64,
    },
  },
  {
    name: "ultimine_upgrade4",
    power: 5,
    permissions: {
      "ftbultimine.max_blocks": 96,
    },
  },
  {
    name: "ultimine_upgrade5",
    power: 6,
    permissions: {
      "ftbultimine.max_blocks": 128,
    },
  },
];

function updateRanks() {
    for (const rank of ranks) {
        let FTBRank = $FTBRanksAPI.manager().getRank(rank.name);

        if (!FTBRank.isPresent()) {
            // console.log(`Creating rank ${rank.name}`)
            FTBRank = $FTBRanksAPI.manager().createRank(rank.name, rank.name, rank.power);
        }
        else {
            // console.log(`Rank ${rank.name} already exists`)
            FTBRank = FTBRank.get()
        }
        for (const [permission, value] of Object.entries(rank.permissions)) {
            // console.log(`Setting permission ${permission} to ${value} for rank ${rank.name}`)
            FTBRank.setPermission(permission, $NumberPermissionValue.of(value));
        }
        $FTBRanksAPI.manager().markRanksDirty();
    }
}


const error = (player, message) => {
  player.sendSystemMessage({ text: "⚠ " + message, color: "red" }, true);
};
const success = (player, message) => {
  player.sendSystemMessage({ text: "✔ " + message, color: "green" }, true);
};
const message = (player, message) => {
  player.sendSystemMessage({ text: message, color: "white" }, true);
};
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
