// Creates and configures custom dimensions

const raw = JsonIO.readJson("kubejs/config/settings.json");
const config = raw ? JSON.parse(raw.toString()) : {};

function hexToRgb(hex) {
  const h = hex.replace("#", "");
  return {
    r: parseInt(h.substring(0, 2), 16),
    g: parseInt(h.substring(2, 4), 16),
    b: parseInt(h.substring(4, 6), 16),
  };
}

var portalColor;

ServerEvents.highPriorityData((event) => {
  if (config.dimensions) {
    config.dimensions.forEach((dimension) => {
      const [modId, dimId] = dimension.id.split(":");

      /////////////////
      /// DIMENSION ///
      /////////////////
      const dimJson = { type: "minecraft:overworld" };
      if (dimension.worldgen)
        dimJson["generator"] = {
          type: "minecraft:flat",
          settings: {
            biome: "minecraft:plains",
            lakes: false,
            features: false,
            structures: {},
            layers: Object.entries(dimension.worldgen).map(
              ([block, count]) => ({
                block: block,
                height: count,
              }),
            ),
          },
        };
      event.addJson(`${modId}:dimension/${dimId}.json`, dimJson);

      //////////////
      /// PORTAL ///
      //////////////
      const portal = dimension.portal;
      if (portal) {
        portalColor = hexToRgb(portal.color);
        event.addJson(`${modId}:portals/${dimId}.json`, {
          block: portal.material,
          dim: dimension.id,
          r: portalColor.r,
          g: portalColor.g,
          b: portalColor.b,
          ignitionType: "FLUID",
          ignitionSource: portal.fluid,
        });
      }
    });
  }
});

//////////////
/// DIMINV ///
//////////////
PlayerEvents.loggedIn((event) => {
  if (config.dimensions) {
    config.dimensions.forEach((dimension) => {
      const [modId, dimId] = dimension.id.split(":");
      const data = event.server.persistentData;
      if (!data.getBoolean(`${dimId}Initialized`)) {
        data.putBoolean(`${dimId}Initialized`, true);
        event.server.scheduleInTicks(20, () => {
          event.server.runCommandSilent(`diminv pool ${dimId} create`);
          event.server.runCommandSilent(
            `diminv pool ${dimId} dimension ${dimension.id} assign`,
          );
          event.server.runCommandSilent(
            `diminv pool ${dimId} gameMode ${dimension.gamemode}`,
          );
          event.server.runCommandSilent(
            `diminv pool ${dimId} progressAdvancements false`,
          );
          event.server.runCommandSilent(
            `diminv pool ${dimId} incrementStatistics false`,
          );
        });
      }
    });
  }
});
