import { ActionFormData } from "@minecraft/server-ui";
import { world } from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";
import * as vector3 from "../vector3";
import * as gld from "../gld";
import * as biome_check from "../biome_check";
import { showApp as main_menu, checkDepletedBattery } from "./main_menu"; 

const gpsName = gld.getAppData("gps");

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
  let playerCoordinates = player.location;
  let rotation = player.getRotation().y;
  let playerFacing = vector3.rotationToFacingAdvanced(rotation);
  let time = utils.getTimeIn12hFormat();
  let currentBiome = getCurrentBiome(player);
  let spawnPoint = player.getSpawnPoint();
  let playerDimension = undefined;

  if(spawnPoint !== undefined) {
    playerDimension = spawnPoint.dimension;
  } else {
		spawnPoint = world.getDynamicProperty("goe_spa_default_spawn");
  }

  let distanceToSpawn = "";
  if (player.dimension.id === "minecraft:overworld") {
    spawnPoint = `${spawnPoint.x} ${spawnPoint.y} ${spawnPoint.y}`
    distanceToSpawn = `\n${getDistanceToSpawn(player)}\n`;
  } else {
    spawnPoint = "Overworld";
  }

  let otherPlayersCoordinates = getOtherPlayersCoordinates(player);

  const GpsApp = new ActionFormData()
  .title(`${gpsName.name}`)
  .body(
    gld.getScreenTitle(player) +
    `\n§bLocation: §e${Math.round(playerCoordinates.x)} ${Math.round(playerCoordinates.y)} ${Math.round(playerCoordinates.z)}\n` +
    `\n§bFacing: §f${playerFacing}\n` +
    `\n§bTime: §c${time}\n` +
    `\n§bBiome: §9${currentBiome}\n` +
    `\n§bSpawn point: §d${spawnPoint}\n` +
    `${distanceToSpawn}` +
    `\n§bOther players location: ${otherPlayersCoordinates}`
  )
  .button("Back", "textures/goe/spa/ui/back");

  GpsApp.show(player).then((response) => {
    inventory_utils.replacePhoneIfUIClosed(player, response);
      let playerPressed = response.selection;

      switch(playerPressed) {
        case 0:
          player.playSound("goe_spa:button_click");
          main_menu(player)
          break;
      }
  })
}

export const biome_tags = [
  "bamboo_jungle",
  "bamboo_jungle_hills",
  "basalt_deltas",
  "beach",
  "birch_forest",
  "birch_forest_hills",
  "birch_forest_hills_mutated",
  "birch_forest_mutated",
  "cherry_grove",
  "cold_beach",
  "cold_ocean",
  "cold_taiga",
  "cold_taiga_hills",
  "cold_taiga_mutated",
  "crimson_forest",
  "deep_cold_ocean",
  "deep_dark",
  "deep_frozen_ocean",
  "deep_lukewarm_ocean",
  "deep_ocean",
  "deep_warm_ocean",
  "desert",
  "desert_hills",
  "desert_mutated",
  "dripstone_caves",
  "extreme_hills",
  "extreme_hills_edge",
  "extreme_hills_mutated",
  "extreme_hills_plus_trees",
  "extreme_hills_plus_trees_mutated",
  "flower_forest",
  "forest",
  "forest_hills",
  "frozen_ocean",
  "frozen_peaks",
  "frozen_river",
  "grove",
  "hell",
  "ice_mountains",
  "ice_plains",
  "ice_plains_spikes",
  "jagged_peaks",
  "jungle",
  "jungle_edge",
  "jungle_edge_mutated",
  "jungle_hills",
  "jungle_mutated",
  "legacy_frozen_ocean",
  "lukewarm_ocean",
  "lush_caves",
  "mangrove_swamp",
  "meadow",
  "mega_taiga",
  "mega_taiga_hills",
  "mesa",
  "mesa_bryce",
  "mesa_plateau",
  "mesa_plateau_mutated",
  "mesa_plateau_stone",
  "mesa_plateau_stone_mutated",
  "mushroom_island",
  "mushroom_island_shore",
  "ocean",
  "plains",
  "redwood_taiga_hills_mutated",
  "redwood_taiga_mutated",
  "river",
  "roofed_forest",
  "roofed_forest_mutated",
  "savanna",
  "savanna_mutated",
  "savanna_plateau",
  "savanna_plateau_mutated",
  "snowy_slopes",
  "soulsand_valley",
  "stone_beach",
  "stony_peaks",
  "sunflower_plains",
  "swampland",
  "swampland_mutated",
  "taiga",
  "taiga_hills",
  "taiga_mutated",
  "the_end",
  "warm_ocean",
  "warped_forest"
]
function getCurrentBiome(player){
  return biome_check.getBiome(player)
    .split('_') // Split the string by underscores
    .map(word => word.charAt(0).toUpperCase() + word.slice(1)) // Capitalize the first letter of each word
    .join(' '); // Join the words back together with spaces
}

function getDistanceToSpawn(player) {
  let playerSpawnPoint = player.getSpawnPoint();
  let dimension = undefined;

  if(playerSpawnPoint !== undefined) {
    dimension = playerSpawnPoint.dimension;
  } else {
    dimension = world.getDimension("overworld");
    playerSpawnPoint = world.getDynamicProperty("goe_spa_default_spawn");
  }

  let playerLocation = player.location;
  let distanceInBlocks = vector3.distance(playerSpawnPoint, playerLocation);
  return "§bDistance to spawn point: §d" + Math.round(distanceInBlocks) + " blocks";
}

function getOtherPlayersCoordinates(player) {
  let allPlayers = world.getAllPlayers();
  let playerLocations = [];

  allPlayers.forEach(p => {
    if(p !== player){
      let location = p.location;
      let name = p.name;
      // Format the string
      let locationString = `\n§f${name}: §e${Math.round(location.x)} ${Math.round(location.y)} ${Math.round(location.z)}§r\n`;
      playerLocations.push(locationString);
    }
  });

   // Check if the list is empty
   if (playerLocations.length === 0) {
    return "\n§fNo other players detected.";
  }

  return playerLocations;
}
