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

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
    // Get all players in the game
    const ALLPLAYERS = world.getAllPlayers().filter(p => p.name !== player.name);

    // Generate a list of player names for display in the dropdown
    const playerNames = ['All players', ...ALLPLAYERS.map(p => p.name)];

    // Generate a list of indexes corresponding to the players
    // Include a special index for "All players"
    const playerIndexes = [-1, ...ALLPLAYERS.map((_, index) => index)];

    let sendToSelector = "";
    let msgText = "";

    let msgName = gld.getAppData("msg");

    const MsgApp = new ModalFormData()
        .title(msgName.name)
        .dropdown(`${gld.getScreenTitle(player)}\n`+ 
            `Use this app to send messages to other players.\n\n` + 
            "§aSend to:§r", playerNames, 0)  // Default to "All players"
        .textField("§bMessage text§r", "Enter text message");

    MsgApp.submitButton("Send");

    MsgApp.show(player).then(formData => {
        inventory_utils.replacePhoneIfUIClosed(player, formData);
        if (formData.formValues) {
            const selectedIndex = playerIndexes[formData.formValues[0]];
            msgText = formData.formValues[1];

            // Handle the "All players" option
            if (selectedIndex === -1) {
                sendToSelector = '@a';  // Special value for all players
            } else {
                sendToSelector = ALLPLAYERS[selectedIndex];
            }
            player.playSound("goe_spa:send_message");

            // Validate and send message
            if (msgText !== "") {
                sendMessage(player, sendToSelector, msgText);
            } else {
                main_menu(player);
            }
        }
    });
}


async function sendMessage(sender, sendTo, msg) {
    const allPlayers = world.getAllPlayers();
    if (sendTo === "@a"){ 
        utils.runPlayerCommand(sender, `msg @a[name=!${sender.name}] ${msg}`);
        allPlayers.forEach(p => {
            p.playSound("goe_spa:receive_message");
        });
        main_menu(sender)
    } else {
        allPlayers.forEach(p => {
            if(p === sendTo){
                utils.runPlayerCommand(sender, `msg @a[name=${sendTo.name}] ${msg}`);
                p.playSound("goe_spa:receive_message");
                main_menu(sender);
            }
        });
    }
}