import { ActionFormData } from "@minecraft/server-ui";
import { world, HudVisibility, HudElement, system, TicksPerSecond } from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";
import { showApp as main_menu, checkDepletedBattery } from "./main_menu"; 
import * as Vector3 from "../vector3";
import * as battery from "../battery";
import * as gld from "../gld";


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

	
	const appData = gld.getAppData("satellite_view");
    let SatelliteForm = new ActionFormData().title(gld.mainMenuApp.name);

    let bodyText = gld.getScreenTitle(player) 
                    + "Use this app to get a wide top view of your area. This can help you find out where you are and locate structures in the distance.\n\n";
					SatelliteForm.body(bodyText);
    SatelliteForm.button("§aActivate ", appData.icon);
    SatelliteForm.button("Back", "textures/goe/spa/ui/back");

    SatelliteForm.show(player).then((response) => {
		inventory_utils.replacePhoneIfUIClosed(player, response);
		player.playSound("goe_spa:button_click");
        if (response.selection == 0) 
			activateSatellite(player);
		else if (response.selection == 1) 
			main_menu(player);
    });
}

async function activateSatellite(player){
	player.playSound("goe_spa:satellite");
	await inventory_utils.storeArmorInMemory(player);
	await inventory_utils.setSatelliteaHud(player);

	player.setDynamicProperty("goe_spa_pre_satellite_location", player.location);
	player.setDynamicProperty("goe_spa_pre_satellite_rotation", player.getRotation().y);

    let satelliteLocation = Vector3.copyFloor(player.location);
    satelliteLocation.y = 190;
    player.dimension.spawnEntity("goe_spa:satellite", satelliteLocation);

	player.addEffect("invisibility", 100000, {amplifier:255, showParticles: false});
	await player.teleport(satelliteLocation, { rotation: {x: 90, y: 90 }});
    player.addTag("goe_spa_satellite_mode");
	player.setDynamicProperty("goe_spa_satelite_slot", player.selectedSlotIndex);
    utils.actionbar(player, "@s", "Press jump or sneak to stop the satellite view.");

	let command = `ride @s start_riding @e[type=goe_spa:satellite,x=${satelliteLocation.x},y=${satelliteLocation.y},z=${satelliteLocation.z},c=1] teleport_rider`;
	await utils.runPlayerCommand(player, command);

	// Hide HUD
	player.onScreenDisplay.setHudVisibility(
		HudVisibility.Hide, 
		[ 
			HudElement.HorseHealth,
			HudElement.Hotbar
		]
	);
}

export async function exitSatellite(player, isValidExit)
{
	player.playSound("goe_spa:satellite_down");
	player.removeTag("goe_spa_exit_satellite");

	let preSatelliteLocation = await player.getDynamicProperty("goe_spa_pre_satellite_location");
	let preSatelliteRotation = await player.getDynamicProperty("goe_spa_pre_satellite_rotation");

    await utils.runPlayerCommand(player, "event entity @e[type=goe_spa:satellite,r=10,c=1] goe_spa:despawn");
	await player.teleport(preSatelliteLocation, { rotation: {x: 0, y: preSatelliteRotation }});
	await player.removeEffect("invisibility");
	
	await player.setDynamicProperty("goe_spa_pre_satellite_location", undefined);
	await player.setDynamicProperty("goe_spa_pre_satellite_rotation", undefined);
	if (isValidExit)
		utils.actionbar(player, "@s", "Satellite View Closed");
	else
	utils.actionbar(player, "@s", "§9Info§r: Connection lost. Please try again");
	player.removeTag("goe_spa_satellite_mode");
	await inventory_utils.restoreArmorFromMemory(player);
	battery.drainAfterSatellite(player);

	main_menu(player);

	system.runTimeout(() => {
		// Reset HUD
		player.onScreenDisplay.setHudVisibility(
			HudVisibility.Reset, 
			[ 
				HudElement.Hotbar
			]
		);
	}, TicksPerSecond * 0.15);
	
}

let actionbarCooldown = 0;
export async function onTick() {
    
	let players = await world.getAllPlayers();
	for (let player of players)
	{
        if (player.hasTag("goe_spa_exit_satellite"))
            await exitSatellite(player, true);

		if (player.hasTag("goe_spa_satellite_mode"))
		{
            await disableSlotChange(player);
			if (actionbarCooldown === 40)
				utils.actionbar(player, "@s", "Press jump or sneak to stop the satellite view.");
		}
    }
	actionbarCooldown = actionbarCooldown === 40 ? 0 : actionbarCooldown+1;
}

async function disableSlotChange(player) {
	const targetSlotIndex = player.getDynamicProperty("goe_spa_satelite_slot");
	player.selectedSlotIndex = targetSlotIndex;
}

export async function onEntityHurt(event)
{
	if (event.hurtEntity.hasTag("goe_spa_satellite_mode"))
		await exitSatellite(event.hurtEntity, false);
}
