import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { system, world, ItemStack, EnchantmentType } from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";
import * as gld from "../gld";
import * as wallet from "../wallet";
import { showApp as main_menu, checkDepletedBattery } from "./main_menu"; 
import { showApp as finances } from "./bank";
import * as delivery from "./delivery";


let builderData = gld.getAppData("builder");

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;

    // Set layout
    const BuilderMarketForm = new ActionFormData().title(builderData.name);
    BuilderMarketForm.body( gld.getScreenTitle(player) 
                            + "§rUse this app to purchase advanced builds.\n\n"
                            + "Build a useful or decorative structure in an instance!§f\n\n" );

    for (const build of gld.builds) {
        let costColor = wallet.canAfford(player, build.cost) ? "§l§a" : "§l§c";
        BuilderMarketForm.button(`§l${build.name}\n${costColor}Cost: ${build.cost}${gld.coinSymbol}§f`, build.icon);
    }

    BuilderMarketForm.button("Back", "textures/goe/spa/ui/back");    

    // Display app
    BuilderMarketForm.show(player).then(result => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        if (result.canceled) 
            return;

        // Get selected index
        const selected = result.selection;
        if (selected === gld.builds.length) { // Back pressed
            player.playSound("goe_spa:button_click");
            main_menu(player);
            return;
        }

        const selectedItem = gld.builds[selected];
        
        const itemName = selectedItem.name;
        const cost = selectedItem.cost;
        let selectedItemName = selectedItem.nameInPackage !== undefined ? selectedItem.nameInPackage : selectedItem.name;

        if (!wallet.canAfford(player, cost)) {
            player.playSound("goe_spa:reject");
            showCantAffordForm(player, itemName, cost);
            return;
        }

        player.playSound("goe_spa:button_click");

        utils.tellraw(player, "@s", `${selectedItemName} Builder §fpurchased.`);

        // Charge player coins
        wallet.charge(player, cost);


        delivery.sendDelivery(player, delivery.DELIVERY_TYPE.building, selectedItem.id, selectedItemName + " Builder", 1);
        
        player.playSound("goe_spa:purchase");

        showApp(player);

    }).catch(error => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        //utils.debug(error.message);
    });
}

async function showCantAffordForm(player, item, cost) {
    const CantAffordForm = new ActionFormData();
    CantAffordForm.title(builderData.name);
    CantAffordForm.body(
        gld.getScreenTitle(player) +
        `\nNot enough Smartcoins (§6${gld.coinSymbol}§r).\n\n` + 
        `  §l§e${item}§r\n\n` + 
        `§cCost:      ${cost} ${gld.coinSymbol}§r\n` + 
        `§4Missing:   ${cost - wallet.getBalance(player)} ${gld.coinSymbol}§r\n\n`
    );
    CantAffordForm.button("§eGet Smartcoins", gld.getAppData("bank").icon);
    CantAffordForm.button("Back", "textures/goe/spa/ui/back");

    CantAffordForm.show(player).then((response) => {
        player.playSound("goe_spa:button_click");

        if (response.selection == 0) {
            finances(player);
            return;
        }

        showApp(player);
    });
}