import { ItemStack, system, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import config from "../config";
import { amountOf, Buttons, getPlayerInventory } from "./my_API";
world.afterEvents.playerPlaceBlock.subscribe(event => {
    giveTabletPen(event);
});
world.beforeEvents.itemUse.subscribe(event => {
    handleTutorialBookUse(event);
});
function handleTutorialBookUse(event) {
    if (event.itemStack.typeId !== 'nps_mot:tutorial_book') {
        return;
    }
    MoreOresAndToolsForm(event.source);
}
function MoreOresAndToolsForm(player) {
    system.run(() => {
        let form = new ActionFormData();
        form.title({ translate: 'item.nps_mot:tutorial_book' });
        form.body({ translate: 'nps_mot:form_body.select_option' });
        form.button(Buttons.presentation.rawtext, Buttons.presentation.iconPath);
        form.button(Buttons.how_to_play.rawtext, Buttons.how_to_play.iconPath);
        form.button(Buttons.patch_notes.rawtext, Buttons.patch_notes.iconPath);
        form.button(Buttons.discord.rawtext, Buttons.discord.iconPath);
        form.button(Buttons.bug_report.rawtext, Buttons.bug_report.iconPath);
        form.button(Buttons.rate_us.rawtext, Buttons.rate_us.iconPath);
        form.button(Buttons.close.rawtext, Buttons.close.iconPath);
        form.show(player).then(response => {
            if (response.canceled) {
                return;
            }
            if (response.selection === undefined) {
                return;
            }
            switch (response.selection) {
                case 0: {
                    showIntroduction(player);
                    break;
                }
                case 1: {
                    HowToPlay.openMainForm(player);
                    break;
                }
                case 2: {
                    viewPatchNotes(player);
                    break;
                }
                case 3: {
                    joinDiscord(player);
                    break;
                }
                case 4: {
                    reportBug(player);
                    break;
                }
                case 5: {
                    rateAddon(player);
                    break;
                }
            }
        });
    });
}
function joinDiscord(player) {
    let form = new ActionFormData();
    form.title({ translate: 'nps_mot:form_body.join_our_discord_community' });
    form.body("§fOur Discord server is a community space where we share updates, " +
        "§fanswer questions, and have discussions about the Add-On. " +
        "§fJoin us to stay informed and be part of the community!\n\n" +
        `§fDiscord Invite Link: ${config.discordLink}`);
    form.button(Buttons.back.rawtext, Buttons.back.iconPath);
    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }
        if (response.selection == undefined) {
            return;
        }
        switch (response.selection) {
            case 0: {
                MoreOresAndToolsForm(player);
                // Back button
                break;
            }
        }
    });
}
function rateAddon(player) {
    let form = new ActionFormData();
    form.title({ translate: 'nps_mot:form_body.rate_us' });
    form.body("§l§6Thank you for using More Ores and Tools!§r\n\n" +
        "§fTo rate us, visit the Marketplace, go to '§6§lMy Content/Owned/Add-Ons§r§f', " +
        "§ffind '§6§lMore Ores and Tools§r§f', and leave a rating.§r\n\n" +
        "§fYour feedback helps us know if you enjoy our content.§r\n\n" +
        "§fYou can also leave comments via the '§6§lSend Feedback to the Creator§r§f' section.§r");
    form.button(Buttons.back.rawtext, Buttons.back.iconPath);
    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }
        if (response.selection == undefined) {
            return;
        }
        switch (response.selection) {
            case 0: {
                MoreOresAndToolsForm(player);
                // Back button
                break;
            }
        }
    });
}
function viewPatchNotes(player) {
    let form = new ActionFormData();
    form.title({ translate: 'nps_mot:form_body.patch_notes' });
    form.body("§fCheck out the latest updates and improvements...\n\n" +
        "§fSelect a version to see the detailed patch notes.");
    const text1 = {
        translate: "nps_mot:gap_form_text",
        with: { rawtext: [{ translate: 'nps_mot:form_button.update_1_1.title' }, { text: '\n' }, { translate: 'nps_mot:form_button.update_1_1.subtitle' }] }
    };
    const text2 = {
        translate: "nps_mot:gap_form_text",
        with: { rawtext: [{ translate: 'nps_mot:form_button.update_1_2.title' }, { text: '\n' }, { translate: 'nps_mot:form_button.update_1_2.subtitle' }]
        }
    };
    form.button(text2, Buttons.update_1_2.iconPath);
    form.button(text1, Buttons.update_1_1.iconPath);
    form.button(Buttons.back.rawtext, Buttons.back.iconPath);
    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }
        if (response.selection == undefined) {
            return;
        }
        switch (response.selection) {
            case 0: {
                viewPatchNotes_2(player);
                break;
            }
            case 1: {
                viewPatchNotes_1(player);
                break;
            }
            case 2: {
                MoreOresAndToolsForm(player);
                // Back button
                break;
            }
        }
    });
}
function viewPatchNotes_1(player) {
    let form = new ActionFormData();
    form.title({ translate: 'nps_mot:form_body.patch_notes.update_1_1' });
    form.body("§fIn this update, we have made the following changes and improvements:\n\n" +
        "§l§eMajor Additions§r\n" +
        "§f- Improved textures.\n" +
        "§f- Added a community Discord server.\n" +
        "§f- Added new ores in the Nether.\n" +
        "§f- Added adamantite armor and tools.\n" +
        "§f- Added a new fuel in the Nether: Sulfur.\n" +
        "§f- Added Amulets: Use your experience to obtain temporary bonuses with amulets, which can be made from ores found in the Nether.\n" +
        "§f- Introduced the tin ingot to make the crafting of bronze ingots more realistic.\n" +
        "§f- Added drops to humanoid monsters: obtain pickaxes, ores, and materials for your new items (configurable in Settings Tool).\n" +
        "§f- Added a Repair Kit to fully repair armors and tools (not craftable, found by killing humanoid monsters, configurable in Settings Tool).\n" +
        "§f- Added Jewels as drops from humanoid monsters (configurable in Settings Tool).\n" +
        "§f- Added Damage Indicators (configurable in Settings Tool).\n" +
        "§f- Added 4 additional difficulty modes: Apocalypse mode makes monsters more resistant to your attacks, setting the stage for new monsters in future updates to make your survival more exciting (configurable in Settings Tool).\n" +
        "§f- Added a Training Mannequin to test your equipment before heading into combat.\n" +
        "§f- Added a Hand Held Lantern to light your incursions.\n\n" +
        "§l§eGameplay Adjustments§r\n" +
        "§f- Revised armor and tool stats.\n" +
        "§f- Armors are no longer subject to malus.\n" +
        "§f- Changed stick recipes: increased the quantities obtainable.\n" +
        "§f- Hammers can no longer break the border blocks.\n" +
        "§f- Modified spawn rules for the Ore Merchant to appear in a more controlled manner.\n" +
        "§f- Modified the Showcase Block for better clarity.\n" +
        "§f- Ore merchant spawns and despawns have been revised.\n" +
        "§f- Fix silk touch bug.\n\n" +
        "§l§eGraphical and Interface Improvements§r\n" +
        "§f- Overhauled the Settings Tool with a graphical update and more available options.\n" +
        "§f- Overhauled the Tutorial Book.\n\n");
    form.button(Buttons.back.rawtext, Buttons.back.iconPath);
    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }
        if (response.selection == undefined) {
            return;
        }
        switch (response.selection) {
            case 0: {
                MoreOresAndToolsForm(player);
                // Back button
                break;
            }
        }
    });
}
function viewPatchNotes_2(player) {
    let form = new ActionFormData();
    form.title({ translate: 'nps_mot:form_body.patch_notes.update_1_2' });
    form.body("§fIn this update, we have made the following changes and improvements:\n\n" +
        "§l§eMajor Additions§r\n" +
        "§f- Added trims to armor.\n" +
        "§f- Added the codex.\n" +
        "§f- Added the magnifying glass. The magnifying glass allows you to get information by pointing at an ore and pressing the 'use' key.\n" +
        "§f- Added different crafting tables.\n" +
        "§f- Added lead carrot: summon a merchant using the carrot.\n\n" +
        "§l§ePerformance Improvements§r\n" +
        "§f- General performance improvements.\n\n" +
        "§l§eGeneration Improvements§r\n" +
        "§f- Ore generation has been greatly improved! Most ores now have an optimal generation layer, making it easier for all miners! Check the codex to know the optimal layers!\n" +
        "§f- Adamantite ore is now immune to explosions from TNT, beds, etc.\n\n" +
        "§l§eTools and Equipment Adjustments§r\n" +
        "§f- Custom tools now work correctly, breaking blocks at the appropriate speed.\n" +
        "§f- Ores mined with the hammer are now affected by the Fortune and Silk Touch enchantments if your hammer has them.\n" +
        "§f- Custom pickaxes and hammers now break vanilla ores and 1.21 blocks at normal speed.\n" +
        "§f- Hammers can no longer break indestructible blocks.\n" +
        "§f- Amulets are now more durable with the Mending and Unbreaking enchantments.\n" +
        "§f- Increased mining time for ores to 3 seconds and 4.5 seconds for deepslate versions.\n\n" +
        "§l§eBlock and Loot Adjustments§r\n" +
        "§f- Fixed the loot tables for deepslate titanium ore and deepslate tungsten ore, which incorrectly gave the normal version of the ore instead of the deepslate version.\n" +
        "§f- The light block now has an empty loot table, which should prevent light blocks from appearing in inventory or on the ground when using the lantern.\n" +
        "§f- The lantern no longer breaks path blocks when moving over them.\n\n" +
        "§l§eMiscellaneous Improvements§r\n" +
        "§f- Fixed graphical issues with some textures.\n" +
        "§f- Corrected the name of the gamerule 'armorEffects': the message referred to the armor malus that have been removed.\n" +
        "§f- Improved the graphical interface of the settings tool menu.\n" +
        "§f- The merchant's announcement message is no longer broadcast to everyone; it is now only visible if you are within 64 blocks of the newly appeared merchant.\n" +
        "§f- Removal of the merchant ore spawn rule");
    form.button(Buttons.back.rawtext, Buttons.back.iconPath);
    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }
        if (response.selection == undefined) {
            return;
        }
        switch (response.selection) {
            case 0: {
                MoreOresAndToolsForm(player);
                // Back button
                break;
            }
        }
    });
}
function reportBug(player) {
    let form = new ActionFormData();
    form.title({ translate: 'nps_mot:form_body.report_bug' });
    form.body("§fPlease visit our Discord server and go to the appropriate section to report any bugs.\n" +
        "§fYou can also leave comments and feedback via the '§6§lSend Feedback to the Creator§r§f' section on the Marketplace by going to the 'More Ores and Tools' Add-On page.\n\n" +
        "§fYour reports are important for us to fix bugs and improve your gaming experience!");
    form.button(Buttons.back.rawtext, Buttons.back.iconPath);
    form.show(player).then(response => {
        if (response.canceled) {
            return;
        }
        if (response.selection == undefined) {
            return;
        }
        switch (response.selection) {
            case 0: {
                MoreOresAndToolsForm(player);
                // Back button
                break;
            }
        }
    });
}
function showIntroduction(player) {
    const bodyText = `§l§eIntroduction§r\nWelcome to the ${config.addonFullName}, an enriching experience for intrepid miners! Explore unknown depths, discover precious ores, forge resilient armor, and powerful tools to face the challenges of this world.\n\n§l§bDiscovering New Ores§r\nDive into the depths of the earth and uncover a range of new precious ores waiting to be mined. From shiny aluminum to sparkling iridium, each ore offers unique opportunities for seasoned miners.\n\n§l§cForging Armor and Tools§r\nUse these new ores to forge sturdy armor that will protect you from underground dangers and efficient tools that will facilitate your exploration. Whether you're seeking the solid defense of platinum armor or the destructive power of the sapphire hammer, you'll find everything you need to thrive in these hostile environments.\n\n§l§6The Incredible Hammer§r\nExperience the power of the Hammer, a fantastic tool capable of breaking blocks in the blink of an eye. With its ability to strike multiple blocks at once, the Hammer is the ultimate tool for miners seeking productivity and efficiency.\n\n§l§9Meet the Ore Merchant§r\nKeep an eye out for the Ore Merchant, a mysterious character who is present from time to time around the villages. He offers unique trades, exchanging rare and precious materials for valuable resources. Don't miss this opportunity to uncover hidden treasures and amazing artifacts!\n\n§l§dConclusion§r\nThis Add-On is an exciting adventure that takes you into a world of discovery and adventure. Get ready to explore, forge, and thrive in an environment rich in possibilities. Let your quest begin!\n\n`;
    system.run(() => {
        let form = new ActionFormData();
        form.title({ translate: `item.nps_mot:tutorial_book` });
        form.body(bodyText);
        form.button(Buttons.close.rawtext, Buttons.close.iconPath);
        form.show(player).then(response => {
            if (response.canceled) {
                return;
            }
            if (response.selection == undefined) {
                return;
            }
            switch (response.selection) {
                case 0: {
                    if (!player.hasTag(config.TutorialPassedTag)) {
                        player.addTag(config.TutorialPassedTag);
                        let playerInventory = getPlayerInventory(player);
                        let tutorialBook = new ItemStack(`nps_mot:tutorial_book`);
                        tutorialBook.setLore(['', config.addonFullName, config.credits]);
                        let showcaseBlockItemstack = new ItemStack(`nps_mot:showcase_block`);
                        showcaseBlockItemstack.setLore(['', config.addonFullName, config.credits]);
                        let settingsTool = new ItemStack(`nps_mot:settings_tool`);
                        settingsTool.setLore(['', config.addonFullName, config.credits]);
                        playerInventory.container.addItem(settingsTool);
                        playerInventory.container.addItem(tutorialBook);
                        playerInventory.container.addItem(showcaseBlockItemstack);
                        player.sendMessage([config.addonPrefix, { translate: `nps_mot:giveTutorialPack` }]);
                    }
                    break;
                }
            }
        });
    });
}
class HowToPlay {
    static openMainForm(player) {
        let form = new ActionFormData();
        form.title({ translate: 'nps_mot:form_button.how_to_play' });
        form.body({ translate: 'nps_mot:form_body.how_to_play' });
        form.button(Buttons.crafting_tables.rawtext);
        form.button(Buttons.back.rawtext, Buttons.back.iconPath);
        form.show(player).then(response => {
            if (response.canceled) {
                return;
            }
            if (response.selection == undefined) {
                return;
            }
            switch (response.selection) {
                case 0: {
                    this.craftingTablesForm(player);
                    break;
                }
                case 1: {
                    MoreOresAndToolsForm(player);
                    break;
                }
            }
        });
    }
    static craftingTablesForm(player) {
        let form = new ActionFormData();
        const titleText = {
            translate: "nps_mot:gap_form_text",
            with: { rawtext: [
                    { translate: 'nps_mot:form_button.how_to_play' },
                    { text: ' - ' },
                    { translate: 'nps_mot:form_button.crafting_tables' }
                ] }
        };
        form.title(titleText);
        const bodyText = {
            translate: "nps_mot:gap_form_text",
            with: { rawtext: [
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_1' }, { text: '\n\n' },
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_2' }, { text: '\n' },
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_3' }, { text: '\n' },
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_4' }, { text: '\n' },
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_5' }, { text: '\n' },
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_6' }, { text: '\n\n' },
                    { translate: 'nps_mot:how_to_play.crafting_tables.line_7' }
                ] }
        };
        form.body(bodyText);
        form.button(Buttons.back.rawtext, Buttons.back.iconPath);
        form.show(player).then(response => {
            if (response.canceled) {
                return;
            }
            if (response.selection == undefined) {
                return;
            }
            this.openMainForm(player);
        });
    }
}
function giveTabletPen(event) {
    if (event.block.typeId != 'nps_mot:showcase_block') {
        return;
    }
    const player = event.player;
    const tabletPen = new ItemStack(`nps_mot:tablet_pen`);
    tabletPen.setLore(['', config.addonFullName, config.credits]);
    const amount = amountOf(tabletPen.typeId, player);
    if (amount != 0) {
        return;
    }
    getPlayerInventory(player).container.addItem(tabletPen);
    player.sendMessage([config.addonPrefix, { translate: 'nps_mot:giveTabletPen' }]);
}
system.runInterval(() => {
    world.getAllPlayers().forEach(player => {
        if (player.hasTag(config.TutorialPassedTag) == false) {
            showIntroduction(player);
        }
        else {
            updatePlayerOnJoin(player);
        }
    });
}, 100);
function updatePlayerOnJoin(player) {
    const LATEST_VERSION = 4; //10-oct-2024: 3 >> 4
    const UPDATE_OBJECTIVE_ID = config.updateObjectiveId;
    let updateObjective = world.scoreboard.getObjective(UPDATE_OBJECTIVE_ID);
    if (!updateObjective) {
        updateObjective = world.scoreboard.addObjective(UPDATE_OBJECTIVE_ID, UPDATE_OBJECTIVE_ID);
    }
    updateObjective.addScore(player, 0);
    const score = updateObjective.getScore(player);
    if (score === undefined || score !== LATEST_VERSION) {
        updateObjective.setScore(player, LATEST_VERSION);
        informAboutTheUpdate(player);
    }
}
function informAboutTheUpdate(player) {
    player.playSound('nps_mot:notification_1', { location: player.location });
    player.sendMessage([config.addonPrefix, { translate: `nps_mot:informAboutTheUpdate` }]);
    //
    let tutorialBook = new ItemStack(`nps_mot:tutorial_book`);
    tutorialBook.setLore(['', config.addonFullName, config.credits]);
    const amountOfTutorialBook = amountOf(tutorialBook.typeId, player);
    if (amountOfTutorialBook == 0) {
        getPlayerInventory(player).container.addItem(tutorialBook);
    }
    //
    let settingsTool = new ItemStack(`nps_mot:settings_tool`);
    settingsTool.setLore(['', config.addonFullName, config.credits]);
    const amountOfSettingsTool = amountOf(settingsTool.typeId, player);
    if (amountOfSettingsTool == 0) {
        getPlayerInventory(player).container.addItem(settingsTool);
    }
}
