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"; 

const weather = ["Clear", "Rain", "Thunder"];
const weather_index = {"Clear": 0, "Rain": 1, "Thunder": 2};

const weatherName = gld.getAppData("weather");

let currentWeatherType = undefined;
let currentWeather = undefined;

let weatherCycle = world.gameRules.doWeatherCycle;

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
    if(currentWeatherType !== undefined){
        currentWeather = currentWeatherType;
    } else {
        currentWeather = "Clear";
    }
    let weatherIndex = weather_index[currentWeather];

    const WeatherApp = new ModalFormData().title(`${weatherName.name}`)
        .dropdown(gld.getScreenTitle(player) + 
            "Use this app to control the current weather and to change the global weather settings.\n\n" +
            "§aChange weather:", weather, weatherIndex)
		.toggle("§bWeather Cycle", weatherCycle);

        WeatherApp.show(player).then(formData => {
            inventory_utils.replacePhoneIfUIClosed(player, formData);
        if (formData.formValues)
        {
            let oldWeather = currentWeather;
            let oldWeatherCycle = weatherCycle;

            player.playSound("goe_spa:submit");

            currentWeather = weather[formData.formValues[0]];
            weatherCycle = formData.formValues[1];
            
            updateParams(player, currentWeather, oldWeather, weatherCycle, oldWeatherCycle);
        }   
    });
}

function updateParams(player, currentWeather, oldWeather, doWeatherCycle, oldWeatherCycle){
    utils.runCommand(`weather ${currentWeather.toLowerCase()}`);
    if (currentWeather !== oldWeather)
        world.sendMessage(`§b${player.name}§r set the weather to §c${currentWeather}`);

    if(doWeatherCycle){
        utils.runPlayerCommand(player, "gamerule doWeatherCycle true");
        if (doWeatherCycle !== oldWeatherCycle)
            world.sendMessage(`§b${player.name}§r changed the Weather Cycle game rule to §cTRUE`);
    } else {
        utils.runPlayerCommand(player, "gamerule doWeatherCycle false");
        if (doWeatherCycle !== oldWeatherCycle)
            world.sendMessage(`§b${player.name}§r changed the Weather Cycle game rule to §cFALSE`);
    }
    main_menu(player);
}

export async function onWeatherChange(event) {
    currentWeatherType = event.newWeather;
}