import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { EntityComponentTypes, system, TicksPerSecond, ItemStack} from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";
import * as gld from "../gld";
import * as battery from "../battery";
import { showApp as showAboutSmartphone } from "./about_smartphone";
import { showApp as showGps, biome_tags } from "./gps";
import { showApp as showGameSettings }  from "./game_settings";
import { showApp as showWeather }  from "./weather";
import { showApp as showDayTime }  from "./day_time";
import { showApp as showFlashlight }  from "./flashlight";
import { showApp as showMsg }  from "./msg";
import { showApp as showMobDetector }  from "./mob_detector";
import { showApp as showBank } from "./bank";
import { showApp as showPlayMusic } from "./play_music";
import { showApp as showWarp }  from "./warp";
import { showApp as showSurvivalStats } from "./survival_stats";
import { showApp as showAppAtore } from "./app_store";
import { showApp as showFitness } from "./fitness";
import { showApp as showEnchantmentStore } from "./enchantment_store";
import { showApp as showEffectStore } from "./effect_store";
import { showApp as showFoodStore } from "./food_store";
import { showApp as showGearMarket } from "./gear_market";
import { showApp as showMemo } from "./memo";
import { showApp as showSatelliteView } from "./satellite";
import { showApp as showGuessTheNumber } from "./guess_the_number";
import { showApp as showMathWizQuiz } from "./math_wiz_quiz";
import { showApp as showColorCustomizer } from "./color_customizer";
import { showApp as showCoinClicker } from "./coin_clicker";
import { showApp as showBuilder } from "./builder";
import { showApp as showRealismSettings } from "./realism";

export async function onItemUse(event) {
    let player = event.source;
    player.playSound("goe_spa:unlock_phone");
    player.setDynamicProperty("goe_spa_phone_slot", player.selectedSlotIndex);
    if(player.hasTag("goe_spa_oppened_first_time")){
        showApp(player);
        system.runTimeout(() => {
            inventory_utils.setPhoneHud(player);
        }, TicksPerSecond * 0.15);
    } else {
        inventory_utils.setPhoneHud(player);
        utils.runPlayerCommand(player, "title @s title §b GO:E＀");
        utils.runPlayerCommand(player, "title @s subtitle  Loading.＀");
        system.runTimeout(() => {
            utils.runPlayerCommand(player, "title @s subtitle  Loading..＀");
        }, TicksPerSecond * 0.5);
        system.runTimeout(() => {
            utils.runPlayerCommand(player, "title @s subtitle  Loading...＀");
        }, TicksPerSecond * 1);
        system.runTimeout(() => {
            player.playSound("goe_spa:confirm");
            utils.runPlayerCommand(player, "title @s clear");
            showLogin(player);
        }, TicksPerSecond * 1.5);
    }
}

export async function showApp(player){

    if (await checkDepletedBattery(player))
        return;

    let MainMenu = new ActionFormData()
    .title(gld.mainMenuApp.name)
    .body(`${gld.getScreenTitle(player)}§fApps:\n`);

    let ownedApps = gld.ownedApps(player);
    for (const ownedApp of ownedApps)
    {
        MainMenu = MainMenu.button(ownedApp.name, ownedApp.icon);
    }

    const appFuncs = { "about_smartphone": showAboutSmartphone, "gps": showGps, "game_settings": showGameSettings, "weather": showWeather,
        "day_time": showDayTime, "flashlight": showFlashlight, "msg": showMsg, "mob_detector": showMobDetector,
        "bank": showBank, "play_music": showPlayMusic, "app_store": showAppAtore, "warp": showWarp, "satellite_view": showSatelliteView,
        "survival_stats": showSurvivalStats, "fitness": showFitness, "enchantment_store": showEnchantmentStore,
        "memo": showMemo, "effect_store": showEffectStore, "food_store": showFoodStore, "gear_market": showGearMarket, 
        "guess_the_number": showGuessTheNumber, "math_wiz_quiz": showMathWizQuiz, "color_customizer": showColorCustomizer,
        "coin_clicker": showCoinClicker, "builder": showBuilder, "realism_settings": showRealismSettings
    }

    MainMenu.show(player).then((response) => {
        inventory_utils.replacePhoneIfUIClosed(player, response);
        let playerPressed = response.selection;
        if (playerPressed == undefined)
            return;
        let selectedAppData = ownedApps[playerPressed];
        let func = appFuncs[selectedAppData.id];
        player.playSound("goe_spa:button_click");
        func(player);
    });

    biome_tags.forEach(biome => {
        player.removeTag(biome);
    });

    //Summon an entity that checks the current biome
    utils.runPlayerCommand(player, "summon goe_spa:biome_check ~ ~ ~");
}

export async function checkDepletedBattery(player) {
    if (battery.getCharge(player) > 1)
        return false;

    let DeplatedForm = new ActionFormData().title(gld.mainMenuApp.name);

    let bodyText = gld.getScreenTitle(player) 
                    + "§l§cYour phone battery is depleted!§r\n\n"
                    + "Use a Smartphone Battery to charge it.\n\n"
                    + "§l§eTip§r: Merge a Smartphone with a Smartphone Battery in a crafting table to charge the Smartphone to full power.\n\n\n";
    DeplatedForm.body(bodyText);
    DeplatedForm.button("Exit");

    DeplatedForm.show(player).then((response) => {
        inventory_utils.replacePhoneIfUIClosed(player, undefined);
        player.playSound("goe_spa:button_click");
    });
    return true;
}

export async function onEntityDie(event)
{
	let player = event.deadEntity;
	player.removeTag("goe_spa_satellite_mode");
	player.removeTag("goe_spa_flashlight_mode");

	let itemEntities = await utils.getEntitiesInRange("minecraft:item", player.dimension, player.location, 0 , 20);
	if (itemEntities === undefined)
        return;
	for (const itemEntity of itemEntities)
	{
		let itemComponent = itemEntity.getComponent(EntityComponentTypes.Item);
		if (itemComponent.itemStack.typeId.endsWith("_smartphone_hud"))
			await inventory_utils.spawnPhoneItemAfterDeath(itemEntity);
	}
}

async function showLogin(player){
    if (await checkDepletedBattery(player))
        return;

    const LoginMenu = new ModalFormData().title(gld.loginMenu.name)
        .textField("§fType your username to log in:\n(Max 10 characters)§r", "Guest");

    LoginMenu.show(player).then(formData => {
        inventory_utils.replacePhoneIfUIClosed(player, formData);
        if (formData.formValues)
        {
            let playerInput = formData.formValues[0].substring(0, 10);
            if (playerInput === "")
                playerInput = "Guest";
            player.playSound("goe_spa:button_click");
            showWelcomePage(player, playerInput);
        }   
    });
}

async function showWelcomePage(player, playerInput){
    player.playSound("goe_spa:intro");

    if (await checkDepletedBattery(player))
        return;

    const WelcomeMenu = new ActionFormData().title(gld.welcomeMenu.name)
        .body(`${gld.getScreenTitle(player)}`+
        `                      §l§bGO:E\n\n§r`+
        `                 §fWelcome §a${playerInput}§r!\n`+
        `              Enjoy your very first `+
        `                   Smartphone in Minecraft.\n`+
        `                  Click on the \n`+
        `         About Smartphone button in the`+
        `             main menu to learn more...\n\n`+
        `§5         Don't forget to give it a §65-star§5`+
        `             rating on the Marketplace.\n`+
        `§6                    ⭐⭐⭐⭐⭐`
    )
        .button("§lGet Started");

    WelcomeMenu.show(player).then((response) => {
        inventory_utils.replacePhoneIfUIClosed(player, response);
        let playerPressed = response.selection;
        switch (playerPressed) {
            case 0:
                player.playSound("goe_spa:outro");
                showAboutSmartphone(player);
                givePlayerReward(player);
                break;
        }
    });
}

async function givePlayerReward(player) {
    const dimension = player.dimension;
    const location = player.location;
    dimension.spawnItem(new ItemStack("goe_spa:battery", 1), location);
    dimension.spawnItem(new ItemStack("minecraft:redstone", 13), location);
    dimension.spawnItem(new ItemStack("goe_spa:coffee", 1), location);
    dimension.spawnItem(new ItemStack("goe_spa:pizza", 5), location);
}