import { world, system, Player, ScoreboardIdentity } from "@minecraft/server"
import { ActionFormData, MessageFormData, ModalFormData } from "@minecraft/server-ui"

 export function weatherTimeSettings(player) {
    let timeLabels = ["Sunrise", "Day", "Noon", "Afternoon", "Sunset", "Night", "Midnight"];
    let weatherLabels = ["Clear", "Rain", "Thunder"];

    let timeSteps = [23600, 1000, 6000, 9000, 12400, 20000, 18000]; // Corresponding Minecraft times
    let weatherSteps = [0, 1, 2]; // Corresponding weather states

    let currentTime = getTime();
    let currentWeather = getWeather();

    let timeIndex = timeSteps.findIndex(t => t >= currentTime);
    if (timeIndex === -1) timeIndex = 0;

    let weatherIndex = weatherSteps.indexOf(currentWeather);
    if (weatherIndex === -1) weatherIndex = 0;

    let form = new ModalFormData()
        .title("§lWeather & Time")
        .dropdown("Set Time", timeLabels, timeIndex)
        .dropdown("Set Weather", weatherLabels, weatherIndex);

    form.show(player).then(response => {
        if (response.canceled) return;

        let selectedTime = timeSteps[response.formValues[0]];
        let selectedWeather = weatherSteps[response.formValues[1]];

        setTime(selectedTime);
        setWeather(selectedWeather);

        player.sendMessage("§eWeather & Time Settings updated");
        player.playSound("random.pop");
        player.runCommandAsync("title @a actionbar §eWeather & Time updated");

      
    });
}

// Function to get current time
function getTime() {
    let result = world.getDimension("overworld").runCommandAsync("time query daytime");
    return result.success ? parseInt(result.statusMessage) : 0;
}

// Function to get current weather state
function getWeather() {
    let weatherState = world.getDynamicProperty("currentWeather") ?? 0;
    return weatherState;
}

// Function to set time
function setTime(value) {
    world.getDimension("overworld").runCommandAsync(`time set ${value}`);
}

// Function to set weather
function setWeather(value) {
    let weatherType = ["clear", "rain", "thunder"][value];
    world.getDimension("overworld").runCommandAsync(`weather ${weatherType}`);
    world.setDynamicProperty("currentWeather", value);
}




