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 daytime = ["Sunrise", "Day", "Noon", "Sunset", "Night", "Midnight"];
const daytime_index = {"Sunrise": 0, "Day": 1, "Noon": 2, "Sunset": 3, "Night": 4, "Midnight": 5};
const dayTimeName = gld.getAppData("day_time");

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
    
    let timeCycle = world.gameRules.doDayLightCycle;
    let currentDayTime = utils.getCurrentDayTime();
    let dayTimeIndex = daytime_index[currentDayTime];

    const DayTimeApp = new ModalFormData().title(`${dayTimeName.name}`)
        .dropdown(gld.getScreenTitle(player) + 
            "Use this app to control the current time and to change the global time settings.\n\n" +
            "§aSet time:", daytime, dayTimeIndex)
		.toggle("§bDo Daylight Cycle", timeCycle);

        DayTimeApp.show(player).then(formData => {
            inventory_utils.replacePhoneIfUIClosed(player, formData);
        if (formData.formValues)
        {
            let oldDayTimeValue = currentDayTime;
            let oldTimeCycleValue = timeCycle;
            currentDayTime = daytime[formData.formValues[0]];
            timeCycle = formData.formValues[1];
            player.playSound("goe_spa:submit");
            updateParams(player, currentDayTime, oldDayTimeValue, timeCycle, oldTimeCycleValue);
        }   
    });
}

function updateParams(player, currentDayTime, oldDayTimeValue, doDayLightCycle, oldTimeCycleValue){
        utils.runCommand(`time set ${currentDayTime.toLowerCase()}`);
        if(currentDayTime !== oldDayTimeValue)
            world.sendMessage(`§b${player.name}§r set the time to §c${currentDayTime}`);

        if(doDayLightCycle){
            utils.runPlayerCommand(player, "gamerule doDayLightCycle true");
            if(doDayLightCycle !== oldTimeCycleValue)
                world.sendMessage(`§b${player.name}§r changed the Day light cycle to §cTRUE`);
        } else {
            utils.runPlayerCommand(player, "gamerule doDayLightCycle false");
            if(doDayLightCycle !== oldTimeCycleValue)
                world.sendMessage(`§b${player.name}§r changed the Day light cycle to §cFALSE`);
        }

        main_menu(player);
}