console.warn("§aFarmer's Delight Add-on§r: Do you have the §6§lcreator settings§r activated? if you find any error let me know on my discord: §bPupy200mine#5915§r. I spent a long time perfecting the addon :)")

import * as server from "@minecraft/server"
import "./item_effects.js"
import "./misc.js"

let actualVersion = "14.9.4"

import './custom_crop';


//Using
// Player method for climb
const climbingPlayers = new Map(); // Rastrea qué jugadores estaban escalando

server.Player.prototype.climb = function () {
    const block = this.dimension.getBlock(this.location);
    const wasClimbing = climbingPlayers.get(this.id) || false;
    const canClimb = block?.hasTag("halo:can_climb") || block?.permutation.getState("farmersdelight:rope");

    if (!canClimb) {
        if (wasClimbing) {
            this.removeEffect("levitation")
            this.removeEffect("slow_falling")
            climbingPlayers.set(this.id, false);
        }
        return
    } // add halo:can_climb tag to ur block, u can change it if u want

    climbingPlayers.set(this.id, true);
    const effect = this.isJumping ? "levitation" : "slow_falling";
    this.addEffect(effect, 1, {
        amplifier: 2,
        showParticles: false,
    });

    if (this.isSneaking && !this.isJumping) {
        this.applyKnockback({ x: 0, y: 0, z: 0 }, 0.02);
    }
};

server.system.runInterval(() => {
    for (const player of server.world.getPlayers()) {
        player.climb(); // Calling the method
    }
});

//We add the tag “checker:warn” to all players every second (it can probably be optimized).
server.system.runInterval(() => {
    try {
        for (let player of server.world.getAllPlayers()) {
            if (player.hasTag("farmer:warn")) return

            player.addTag(`farmer:warn`)
        }
    } catch { }
}, 20)

//We send a message to the player that the addon is working.
server.world.afterEvents.playerJoin.subscribe(result => {
    let interval = server.system.runInterval(() => {
        try {
            let player = server.world.getPlayers({ name: result.playerName })[0]

            player.sendMessage("§aFarmer's Delight Add-on§r §aloaded successfully!")

            server.system.clearRun(interval)
        } catch { }
    })
})

server.world.beforeEvents.playerInteractWithEntity.subscribe(result => {

    if (!result.itemStack) return

    if (result.target.typeId == "minecraft:horse" && result.itemStack.typeId == "farmersdelight:horse_feed") {
        server.system.run(() => {
            if (result.itemStack.amount == 1)
                result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, undefined)
            else {
                result.itemStack.amount--
                result.player.getComponent(server.EntityInventoryComponent.componentId).container.setItem(result.player.selectedSlotIndex, result.itemStack)
            }
            result.target.dimension.playSound("mob.horse.eat", result.target.location)
            result.target.addEffect("minecraft:speed", 300, { showParticles: false, amplifier: 1 })
            result.target.addEffect("minecraft:jump_boost", 300, { showParticles: false })
        })
        result.cancel = true
    }
})

let i = 0
server.world.beforeEvents.playerBreakBlock.subscribe(result => {
    let player = result.player
    let item = result.itemStack

    let wildPlants = [
        "farmersdelight:wild_beetroots",
        "farmersdelight:wild_cabbages",
        "farmersdelight:wild_carrots",
        "farmersdelight:wild_onions",
        "farmersdelight:wild_potatoes",
        "farmersdelight:wild_rice",
        "farmersdelight:wild_tomatoes",
    ]

    if (item?.typeId == "minecraft:shears" && wildPlants.includes(result.block.typeId)) {
        result.cancel = true
        if (i == 0) {
            server.system.run(() => {
                result.block.dimension.spawnItem(new server.ItemStack(result.block.typeId, 1), result.block.center())
                result.dimension.setBlockType(result.block.location, "minecraft:air")
                result.dimension.playSound("dig.grass", result.block.center())

                //Using https://discord.com/channels/523663022053392405/1072983602821861426/threads/1223615470155075595 template to break the item
                // This retrieves the player's equippable component.
                // This retrieves the player's equippable component.
                const playerEquippableComp = player.getComponent("equippable");

                // This returns if playerEquippableComp is undefined.
                if (!playerEquippableComp) return;

                // This retrieves the enchantable component of the item.
                const itemEnchantmentComp = item.getComponent("minecraft:enchantable");
                const unbreakingLevel = itemEnchantmentComp?.getEnchantment("unbreaking")?.level ?? 0;

                // Calculates the chance of an item breaking based on its unbreaking level. This is the vanilla unbreaking formula.
                const breakChance = 100 / (unbreakingLevel + 1);
                // Generates a random chance value between 0 and 100.
                const randomizeChance = Math.random() * 100;

                // This returns if breakChance is less than randomizeChance.
                if (breakChance < randomizeChance) return;

                // This retrieves the durability component of the item.
                const itemUsedDurabilityComp = item.getComponent("durability");

                // This returns if itemUsedDurabilityComp is undefined.
                if (!itemUsedDurabilityComp) return;

                // This will set the new durability value.
                itemUsedDurabilityComp.damage += 1;

                // Declares and checks if the item is out of durability
                const maxDurability = itemUsedDurabilityComp.maxDurability
                const currentDamage = itemUsedDurabilityComp.damage
                if (currentDamage >= maxDurability) {

                    // If the item is out of durability, plays the item breaking sound and removes the item
                    player.playSound('random.break', { pitch: 1, location: player.location, volume: 1 })
                    playerEquippableComp.setEquipment("Mainhand", new server.ItemStack('minecraft:air', 1));
                }
                else if (currentDamage < maxDurability) {

                    // This sets the item in the player's selected slot.
                    playerEquippableComp.setEquipment("Mainhand", item);
                }
            })
            i++
        }
        else {
            i = 0
        }
    }
})

server.world.afterEvents.playerBreakBlock.subscribe(result => {
    if (result.brokenBlockPermutation.type.id == "minecraft:soul_campfire" || result.brokenBlockPermutation.type.id == "minecraft:campfire") {
        let above = result.block.above(1)
        if (above.typeId == "farmersdelight:skillet" || above.typeId == "farmersdelight:cooking_pot") {
            let state = above.permutation.getAllStates()
            state["block:is_campfire"] = false
            const permutation = server.BlockPermutation.resolve(above.typeId, state)
            above.setPermutation(permutation)
        }
    }
})

//Tomatoes
server.world.afterEvents.playerInteractWithBlock.subscribe(result => {
    if (result.block.typeId != "farmersdelight:tomatoes_plant") return
    let state = result.block.permutation.getAllStates()
    if (state["customcrop:growth"] == 7) {
        state["customcrop:growth"] = 4
        result.block.setPermutation(server.BlockPermutation.resolve(result.block.typeId, state))
        result.block.dimension.spawnItem(new server.ItemStack("farmersdelight:tomato", Math.floor(Math.random() * 2) + 1), result.block.location)
    }
})

import {
    ActionFormData
} from '@minecraft/server-ui'
//Obtener Straw al romper Tallgrass
server.world.beforeEvents.playerBreakBlock.subscribe(result => {
    let state = {
        "double_plant_type": "grass"
    }
    if (result.block.typeId == "minecraft:tallgrass" || result.block.permutation.matches("minecraft:double_plant", state)) {
        result.itemStack?.getTags().forEach(tag => {
            if (tag == "fd_knife") {
                let num = Math.floor(Math.random() * 12) + 1
                if (num == 1) {
                    server.system.run(() => {
                        result.block.dimension.spawnItem(new server.ItemStack("farmersdelight:straw", 1), result.block.location)
                    })
                }
            }
        })
    }
})

// server.world.beforeEvents.playerBreakBlock.subscribe(result => {
//     if (!result.itemStack || !result.itemStack.getComponent("minecraft:enchantable")) return

//     if (result.itemStack.getComponent("minecraft:enchantable").hasEnchantment("silk_touch") && result.block.hasTag("fd_silk_touch")) {
//         server.system.run(() => {
//             if (result.block.typeId == "farmersdelight:wild_rice_plant" || result.block.typeId == "minecraft:water") result.block.dimension.setBlockType(result.block.location, "minecraft:water")
//             else result.block.dimension.setBlockType(result.block.location, "minecraft:air")
//         })
//         result.cancel = true
//     }
// })

server.world.afterEvents.playerPlaceBlock.subscribe(result => {
    if (result.block.typeId == "farmersdelight:skillet") {
        result.block.dimension.spawnEntity("farmersdelight:skillet", { x: result.block.x + 0.30, y: result.block.y, z: result.block.z + 0.30 }).triggerEvent("farmersdelight:skillet_1")
        result.block.dimension.spawnEntity("farmersdelight:skillet", { x: result.block.x + 0.30, y: result.block.y, z: result.block.z + 0.70 }).triggerEvent("farmersdelight:skillet_2")
        result.block.dimension.spawnEntity("farmersdelight:skillet", { x: result.block.x + 0.70, y: result.block.y, z: result.block.z + 0.30 }).triggerEvent("farmersdelight:skillet_3")
        result.block.dimension.spawnEntity("farmersdelight:skillet", { x: result.block.x + 0.70, y: result.block.y, z: result.block.z + 0.70 }).triggerEvent("farmersdelight:skillet_4")
    }
    else if (result.block.typeId == "farmersdelight:stove") {

        let rotation = result.block.permutation.getState("block:rotation"); // 2, 3, 4, 5

        const spacingX = 1 / 2;
        const spacingZ = 1 / 3;

        for (let row = 0; row < 3; row++) {
            for (let col = 0; col < 2; col++) {
                let selectedColor = row * 2 + col + 1;

                let localX = (col + 0.5) * spacingX - 0.5;
                let localZ = (row + 0.5) * spacingZ - 0.5;

                let rotated = { x: 0, z: 0 };
                switch (rotation) {
                    case 2:
                        rotated.x = -localZ;
                        rotated.z = localX;
                        break;
                    case 3:
                        rotated.x = localZ;
                        rotated.z = -localX;
                        break;
                    case 4:
                        rotated.x = localX;
                        rotated.z = localZ;
                        break;
                    case 5:
                        rotated.x = -localX;
                        rotated.z = -localZ;
                        break;
                    default:
                        rotated.x = localX;
                        rotated.z = localZ;
                }

                let x = result.block.x + 0.5 + rotated.x;
                let z = result.block.z + 0.5 + rotated.z;

                result.block.dimension.spawnEntity("farmersdelight:stove", {
                    x: x,
                    y: result.block.y + 0.92,
                    z: z
                }).triggerEvent(`farmersdelight:stove_${selectedColor}`);
            }
        }
    }
    else if (result.block.typeId == "farmersdelight:cutting_board") {
        result.block.dimension.spawnEntity("farmersdelight:cutting_board_entity", { x: result.block.x + 0.50, y: result.block.y, z: result.block.z + 0.50 })
    }
})

//Obtener Ham al matar un cerdo con un cuchillo
server.world.afterEvents.entityDie.subscribe(result => {
    if (result.deadEntity.typeId == "minecraft:pig") {
        let item = result.damageSource.damagingEntity.getComponent(server.EntityComponentTypes.Equippable).getEquipment(server.EquipmentSlot.Mainhand)
        if (item) {
            item.getTags().forEach(tag => {
                if (tag == "fd_knife") {
                    const ham = new server.ItemStack("farmersdelight:ham", 1)

                    result.deadEntity.dimension.spawnParticle("farmersdelight:pig_kill", result.deadEntity.location)
                    result.deadEntity.dimension.spawnItem(ham, result.deadEntity.location)
                }
            })
        }
    }
})

//Comportamiento de la tabla de cortar
server.world.afterEvents.playerPlaceBlock.subscribe(result => {
    let { x, y, z } = result.block.location
    result.block.getTags().forEach(tag => {
        if (tag == "fd_cabinet") {
            result.block.dimension.spawnEntity("farmersdelight:inventory", { x: x + 0.5, y: y + 0.5, z: z + 0.5 })
        }
    })
})
server.system.afterEvents.scriptEventReceive.subscribe(result => {
    if (result.id == "farmersdelight:firstJoin" && !result.sourceEntity.hasTag("farmersdelight")) {
        firstJoin(result.sourceEntity)
    }
    else if (result.id == "farmersdelight:book") {
        showBook(result.sourceEntity)
    }
})

server.world.afterEvents.playerSpawn.subscribe(result => {
    server.system.runTimeout(() => {
        if (!result.player.hasTag("farmersdelight")) {
            firstJoin(result.player)
        }
    }, 180)
})

server.world.afterEvents.itemStartUse.subscribe(result => {
    if (result.itemStack.typeId == "farmersdelight:farmers_book") showBook(result.source)
})

/**
* @param {server.Player} player
*/
function firstJoin(player) {
    const firstJoin = new ActionFormData()
        .title("§2Farmers Delight Bedrock")
        .body({ "rawtext": [{ "translate": "delight.welcome0" }, { "text": "\n" }, { "translate": "delight.welcome1", "with": [actualVersion] }, { "text": "\n" }, { "translate": "delight.welcome2" }, { "text": "\n" }, { "translate": "delight.welcome3" }] })
        .button("accessibility.button.close", "textures/ui/exit")

    player.runCommand("gamerule sendcommandfeedback false")
    player.runCommand("gamerule recipesunlock false")
    player.getComponent("inventory").container.addItem(new server.ItemStack("farmersdelight:farmers_book", 1))
    player.addTag("farmersdelight")

    firstJoin.show(player).then(response => {

        if (response.canceled) installedAddons();

        switch (response.selection) {
            case 0:
                installedAddons()
                break;
        }
    })

    function installedAddons() {
        let nethersDelightBedrock = server.BlockTypes.get("nethersdelight:blackstone_stove") ? "farmersdelight.installed" : "farmersdelight.notinstalled";
        let endsDelightBedrock = server.BlockTypes.get("ends_delight:chorus_fruit_crate") ? "farmersdelight.installed" : "farmersdelight.notinstalled";
        let sunflowerDelightBedrock = server.BlockTypes.get("sunflowerdelight:sunflower_seed_bag") ? "farmersdelight.installed" : "farmersdelight.notinstalled";
        let brewinAndChewinBedrock = server.BlockTypes.get("brewinandchewin:keg") ? "farmersdelight.installed" : "farmersdelight.notinstalled";
        let crabbersDelightBedrock = server.BlockTypes.get("crabbersdelight:pearl_block") ? "farmersdelight.installed" : "farmersdelight.notinstalled";
        let largeMealsBedrock = server.BlockTypes.get("largemeals:omurice_block") ? "farmersdelight.installed" : "farmersdelight.notinstalled";
        let spanishDelightBedrock = server.BlockTypes.get("spanishdelight:green_bean_plant") ? "farmersdelight.installed" : "farmersdelight.notinstalled";

        let installations = [
            nethersDelightBedrock,
            endsDelightBedrock,
            sunflowerDelightBedrock,
            brewinAndChewinBedrock,
            crabbersDelightBedrock,
            largeMealsBedrock,
            spanishDelightBedrock
        ];

        let installedCount = installations.filter(status => status === "farmersdelight.installed").length;
        let notInstalledCount = installations.filter(status => status === "farmersdelight.notinstalled").length;

        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.nethersDelightBedrock" }, { "translate": `${nethersDelightBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.endsDelightBedrock" }, { "translate": `${endsDelightBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.sunflowerDelightBedrock" }, { "translate": `${sunflowerDelightBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.brewinAndChewinBedrock" }, { "translate": `${brewinAndChewinBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.crabbersDelightBedrock" }, { "translate": `${crabbersDelightBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.largeMealsBedrock" }, { "translate": `${largeMealsBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.spanishDelightBedrock" }, { "translate": `${spanishDelightBedrock}` }, { "text": "\n " }] })
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.installedCount", "with": [`${installedCount}`] }] })

        if (notInstalledCount > 0) {
            player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.downloadMissingAddons" }] })
        }
        player.sendMessage({ "rawtext": [{ "translate": "farmersdelight.message" }] })
    }
}

/**
* @param {server.Entity} player
*/
function showBook(player) {
    const showBook = new ActionFormData()
        .title("farmersbook.name")
        .body("farmersbook.body")
        .button("farmersbook.introduction", "textures/ui/introduction")
        //.button("farmersbook.howToPlantAddonCrops", "textures/ui/farmland_for_ui")
        .button("farmersbook.howToUseCuttingBoard", "textures/ui/cutting_board_for_ui")
        .button("farmersbook.howToUseCookingPot", "textures/ui/cooking_pot_for_ui")
        .button("farmersbook.howToUseSkillet", "textures/ui/skillet_for_ui")
        .button("farmersbook.howCabinetsWork", "textures/ui/cabinet_for_ui")
        .button("farmersbook.howToUseOrganicCompost", "textures/ui/organic_compost_for_ui")
        .button("farmersbook.howToCreateMushroomColony", "textures/blocks/mushroom_colony/red_mushroom_colony_stage3")
        .button("farmersbook.howTogetHam", "textures/items/ham")
        .button("farmersbook.cabbageandbeetroots", "textures/items/wild_cabbages")
        .button("farmersbook.potatoes", "textures/items/wild_potatoes")
        .button("farmersbook.carrotandonions", "textures/items/wild_carrots")
        .button("farmersbook.tomatoes", "textures/items/wild_tomatoes")
        .button("farmersbook.rice", "textures/items/wild_rice")
        .button("farmersbook.DontClickMe", "textures/items/bread")

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

        switch (response.selection) {
            case 0:
                introduction(player)
                break
            // case 1:
            //     howToPlantAddonCrops(player)
            //     break;
            case 1:
                howToUseCuttingBoard(player)
                break;
            case 2:
                howToUseCookingPot(player)
                break;
            case 3:
                howToUseSkillet(player)
                break;
            case 4:
                howCabinetsWork(player)
                break;
            case 5:
                howToUseOrganicCompost(player)
                break;
            case 6:
                howToCreateMushroomColony(player)
                break;
            case 7:
                howToGetHam(player)
                break;
            case 8:
                cabbageandbeetroots(player)
                break;
            case 9:
                potatoes(player)
                break;
            case 10:
                carrotandonions(player)
                break;
            case 11:
                tomatoes(player)
                break;
            case 12:
                rice(player)
                break;
            case 13:
                test(player)
                break;
        }
    })
}
function introduction(player) {
    const introduction = new ActionFormData()
        .title("§2Farmers Delight Bedrock")
        .body({ "rawtext": [{ "translate": "delight.welcome0" }, { "text": "\n" }, { "translate": "delight.welcome1", "with": [actualVersion] }, { "text": "\n" }, { "translate": "delight.welcome2" }, { "text": "\n" }, { "translate": "delight.welcome3" }] })
        .button("accessibility.button.back", "textures/ui/exit");
    introduction.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howToPlantAddonCrops(player) {
    const howToPlantAddonCrops = new ActionFormData()
        .title("farmersbook.howToPlantAddonCrops")
        .body("farmersbook.howToPlantAddonCropsDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howToPlantAddonCrops.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howToUseCuttingBoard(player) {
    const howToUseCuttingBoard = new ActionFormData()
        .title("farmersbook.howToUseCuttingBoard")
        .body("farmersbook.howToUseCuttingBoardDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howToUseCuttingBoard.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howToUseCookingPot(player) {
    const howToUseCookingPot = new ActionFormData()
        .title("farmersbook.howToUseCookingPot")
        .body("farmersbook.howToUseCookingPotDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howToUseCookingPot.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howToUseSkillet(player) {
    const howToUseSkillet = new ActionFormData()
        .title("farmersbook.howToUseSkillet")
        .body("farmersbook.howToUseSkilletDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howToUseSkillet.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howCabinetsWork(player) {
    const howCabinetsWork = new ActionFormData()
        .title("farmersbook.howCabinetsWork")
        .body("farmersbook.howCabinetsWorkDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howCabinetsWork.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howToUseOrganicCompost(player) {
    const howToUseOrganicCompost = new ActionFormData()
        .title("farmersbook.howToUseOrganicCompost")
        .body("farmersbook.howToUseOrganicCompostDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howToUseOrganicCompost.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function howToCreateMushroomColony(player) {
    const howToCreateMushroomColony = new ActionFormData()
        .title("farmersbook.howToCreateMushroomColony")
        .body("farmersbook.howToCreateMushroomColonyDescription")
        .button("farmersbook.howToUseOrganicCompost")
        .button("accessibility.button.back", "textures/ui/exit");
    howToCreateMushroomColony.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                howToUseOrganicCompost(player)
            }
            else if (response.selection == 1) {
                showBook(player)
            }
        }
    })
}

function howToGetHam(player) {
    const howToGetHam = new ActionFormData()
        .title("farmersbook.howToGetHam")
        .body("farmersbook.howToGetHamDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    howToGetHam.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function cabbageandbeetroots(player) {
    const cabbageandbeetroots = new ActionFormData()
        .title("farmersbook.cabbageandbeetroots")
        .body("farmersbook.cabbageandbeetrootsDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    cabbageandbeetroots.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function potatoes(player) {
    const potatoes = new ActionFormData()
        .title("farmersbook.potatoes")
        .body("farmersbook.potatoesDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    potatoes.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function carrotandonions(player) {
    const carrotandonions = new ActionFormData()
        .title("farmersbook.carrotandonions")
        .body("farmersbook.carrotandonionsDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    carrotandonions.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function tomatoes(player) {
    const tomatoes = new ActionFormData()
        .title("farmersbook.tomatoes")
        .body("farmersbook.tomatoesDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    tomatoes.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

function rice(player) {
    const rice = new ActionFormData()
        .title("farmersbook.rice")
        .body("farmersbook.riceDescription")
        .button("accessibility.button.back", "textures/ui/exit");
    rice.show(player).then(response => {
        if (!response.canceled) {
            if (response.selection == 0) {
                showBook(player)
            }
        }
    })
}

/**
* @param {server.Entity} player
*/
function test(player) {
    let entities = player.dimension.getEntities({ location: player.location, maxDistance: 10 }).filter(entity => entity.typeId === "minecraft:villager_v2").length
    if (entities == 0) {
        player.runCommand(`titleraw @s actionbar {"rawtext":[{"translate":"farmersbook.needVillager"}]}`)
    }
    else {
        player.runCommand("stopsound @a[r=16] DoNotReproduceMe")
        player.runCommand("stopsound @a[r=16] DoNotReproduceMe2")
        player.runCommand("stopsound @a[r=16] DoNotReproduceMe3")
        server.system.runTimeout(() => {

            let random = Math.floor(Math.random() * 3) + 1;

            switch (random) {
                case 1:
                    player.runCommand("playsound DoNotReproduceMe")
                    player.runCommand("playanimation @e[r=10] animation.piglin.celebrate_hunt_special f 38")
                    player.runCommand("title @s actionbar ♪ TIN TAN - El Panadero ♪ (1/3)")
                    break;
                case 2:
                    player.runCommand("playsound DoNotReproduceMe2")
                    player.runCommand("playanimation @e[r=10] animation.piglin.celebrate_hunt_special f 51")
                    player.runCommand("title @s actionbar ♪ La noche más linda del mundo ♪ (2/3)")
                    break;
                case 3:
                    player.runCommand("playsound DoNotReproduceMe3")
                    player.runCommand("playanimation @e[r=10] animation.piglin.celebrate_hunt_special f 46")
                    player.runCommand("title @s actionbar ♪ Olvídala, Binomio De Oro De América ♪ (3/3)")
                    break;
            }
        }, 2)
    }
}