import * as ui from "@minecraft/server-ui";
import { world, system } from "@minecraft/server";
import {
    notificationMessage
} from "./common";

export function openGuidebookMenu(player) {
    // Create menu
    const guidebookMenu = new ui.ActionFormData();
    guidebookMenu.title({ rawtext: [{ translate: "forms.guidebookMenu.title" }] });

    // Populate with GUI Elements
    guidebookMenu.body(
        {
            rawtext: [
                { translate: "forms.guidebookMenu.body", with: ["\n"] }
            ]
        }
    );

    guidebookMenu.button({ rawtext: [{ translate: "forms.button.guidebookMenu.playerSettings" }] }, "textures/octovon/spcrs/forms/button_icon_settings_player");
    guidebookMenu.button({ rawtext: [{ translate: "forms.button.guidebookMenu.addonSettings" }] }, "textures/octovon/spcrs/forms/button_icon_settings_addon");
    guidebookMenu.button({ rawtext: [{ translate: "forms.button.guidebookMenu.changelog" }] }, "textures/octovon/spcrs/forms/button_icon_changelog");


    // Create and Show menu
    guidebookMenu.show(player).then(result => {
        // Action mappings
        if (result.canceled)
            return;

        switch (result.selection) {
            case 0:
                openGuidebookMenuPlayerSettings(player);
                break;
            case 1:
                openGuidebookMenuAddonSettings(player);
                break;
            case 2:
                openGuidebookMenuChangelog(player);
                break;
        }
    });
}
function openGuidebookMenuPlayerSettings(player) {
    // Fetch properties
    const carCameraSetting = player.getDynamicProperty('oct_spcrs:setting.disable_car_camera');
    const speedometerSetting = player.getDynamicProperty('oct_spcrs:setting.disable_speedometer');

    // Create menu
    const guidebookMenuSettings = new ui.ModalFormData();
    guidebookMenuSettings.title({ rawtext: [{ translate: "forms.guidebookMenu.playerSettings.title" }] });

    // Populate with GUI Elements
    guidebookMenuSettings.toggle({ rawtext: [{ "translate": "forms.guidebookMenu.playerSettings.toggle.carCameraSetting", "with": ["\n"] }] }, carCameraSetting);
    guidebookMenuSettings.toggle({ rawtext: [{ "translate": "forms.guidebookMenu.playerSettings.toggle.speedometerSetting", "with": ["\n"] }] }, speedometerSetting);

    // Submit Button
    guidebookMenuSettings.submitButton({ rawtext: [{ translate: "forms.button.guidebookMenu.playerSettings.submit", with: ["\n"] }] });

    // Create and Show menu
    guidebookMenuSettings.show(player).then((result) => {
        // Action mappings
        if (result.canceled) {
            return;
        } else {
            // Apply settings
            const carCamera = result.formValues[0];
            const speedometer = result.formValues[1];
            player.setDynamicProperty('oct_spcrs:setting.disable_car_camera', carCamera);
            player.setDynamicProperty('oct_spcrs:setting.disable_speedometer', speedometer);


            // Send a message
            const sucMessage = { rawtext: [{ "translate": "message.oct_spcrs.settings_updated_player" }] };
            notificationMessage(sucMessage, player);

            return;
        }
    });
}
function openGuidebookMenuAddonSettings(player) {
    // Fetch properties
    const runOverSetting = world.getDynamicProperty('oct_spcrs:setting.disable_run_over');
    const rubberSetting = world.getDynamicProperty('oct_spcrs:setting.disable_rubber');

    // Define the number of cars
    const totalCars = 24;

    // Parse and initialize fuelSetting
    let fuelSetting = [];
    try {
        const storedFuelSetting = JSON.parse(world.getDynamicProperty('oct_spcrs:setting.disable_fuel') || '[]');
        fuelSetting = Array.from({ length: totalCars }, (_, i) => storedFuelSetting[i] || false);
    } catch (error) {
        console.error("Failed to parse fuel settings, initializing to default:", error);
        fuelSetting = Array(totalCars).fill(false);
    }

    // Parse and initialize nitroSetting
    let nitroSetting = [];
    try {
        const storedNitroSetting = JSON.parse(world.getDynamicProperty('oct_spcrs:setting.disable_nitro') || '[]');
        nitroSetting = Array.from({ length: totalCars }, (_, i) => storedNitroSetting[i] || false);
    } catch (error) {
        console.error("Failed to parse nitro settings, initializing to default:", error);
        nitroSetting = Array(totalCars).fill(false);
    }

    // Create menu
    const guidebookMenuSettings = new ui.ModalFormData();
    guidebookMenuSettings.title({ rawtext: [{ translate: "forms.guidebookMenu.addonSettings.title" }] });

    // Populate with GUI Elements
    guidebookMenuSettings.toggle({ rawtext: [{ "translate": "forms.guidebookMenu.addonSettings.toggle.runOverSetting", "with": ["\n"] }] }, runOverSetting);
    guidebookMenuSettings.toggle({ rawtext: [{ "translate": "forms.guidebookMenu.addonSettings.toggle.rubberSetting", "with": ["\n"] }] }, rubberSetting);

    // Add toggles for fuel settings
    fuelSetting.forEach((setting, index) => {
        guidebookMenuSettings.toggle(
            {
                rawtext: [{
                    "translate": "forms.guidebookMenu.addonSettings.toggle.fuelSetting",
                    "with": {
                        "rawtext": [
                            { "text": `${index + 1 === totalCars ? "\n\n\n" : ""}` },
                            { "translate": `entity.oct_spcrs:car_${index + 1}.name` }
                        ]
                    }
                }]
            },
            setting
        );
    });

    nitroSetting.forEach((setting, index) => {
        guidebookMenuSettings.toggle(
            {
                rawtext: [{
                    "translate": "forms.guidebookMenu.addonSettings.toggle.nitroSetting",
                    "with": {
                        "rawtext": [
                            { "text": `${index + 1 === totalCars ? "\n\n\n" : ""}` },
                            { "translate": `entity.oct_spcrs:car_${index + 1}.name` }
                        ]
                    }
                }]
            },
            setting
        );
    });

    // Submit Button
    guidebookMenuSettings.submitButton({ rawtext: [{ translate: "forms.button.guidebookMenu.addonSettings.submit", with: ["\n"] }] });

    // Create and Show menu
    guidebookMenuSettings.show(player).then((result) => {
        // Action mappings
        if (result.canceled) {
            return;
        } else {
            // Extract toggled values
            const updatedRunOverSetting = result.formValues[0];
            const updatedRubberSetting = result.formValues[1];
            const updatedFuelSetting = [];
            const updatedNitroSetting = [];

            // Calculate indices for fuel and nitro toggles
            const fuelStartIndex = 2;
            const nitroStartIndex = fuelStartIndex + fuelSetting.length;

            result.formValues.forEach((value, index) => {
                if (index >= fuelStartIndex && index < nitroStartIndex) {
                    updatedFuelSetting.push(value);
                } else if (index >= nitroStartIndex) {
                    updatedNitroSetting.push(value);
                }
            });

            // Save updated settings
            world.setDynamicProperty('oct_spcrs:setting.disable_run_over', updatedRunOverSetting);
            world.setDynamicProperty('oct_spcrs:setting.disable_rubber', updatedRubberSetting);
            world.setDynamicProperty('oct_spcrs:setting.disable_fuel', JSON.stringify(updatedFuelSetting));
            world.setDynamicProperty('oct_spcrs:setting.disable_nitro', JSON.stringify(updatedNitroSetting));

            // Send success message
            const sucMessage = { rawtext: [{ translate: "message.oct_spcrs.settings_updated_player" }] };
            notificationMessage(sucMessage, player);

            return;
        }
    });
}
function openGuidebookMenuChangelog(player) {
    // Create menu
    const guidebookMenuChangelog = new ui.ActionFormData();
    guidebookMenuChangelog.title({ rawtext: [{ translate: "forms.guidebookMenu.changelog.title" }] });

    // Populate with GUI Elements
    guidebookMenuChangelog.body(
        {
            rawtext: [
                {
                    translate: "forms.guidebookMenu.changelog.header", "with": {
                        "rawtext": [
                            { text: "\n" },
                            { translate: "forms.guidebookMenu.changelog.versionNumber" }
                        ]
                    }
                },
                { translate: "forms.divider", with: ["\n"] },
                { translate: "forms.guidebookMenu.changelog.version.2.1.0", with: ["\n"] },
                { translate: "forms.divider", with: ["\n"] },
                { translate: "forms.guidebookMenu.changelog.version.2.0.0", with: ["\n"] },
                { translate: "forms.divider", with: ["\n"] },
                { translate: "forms.divider", with: ["\n"] },
            ]
        }
    );

    guidebookMenuChangelog.button({ rawtext: [{ translate: "forms.button.back" }] });
    guidebookMenuChangelog.button({ rawtext: [{ translate: "forms.button.exit" }] });


    // Create and Show menu
    guidebookMenuChangelog.show(player).then(result => {
        // Action mappings
        if (result.canceled || result.selection === 1)
            return;

        switch (result.selection) {
            case 0:
                openGuidebookMenu(player);
                break;
        }
    });
}