import { EquipmentSlot, GameMode, ItemStack, system } from "@minecraft/server";

/**
 * @param {number} min The minimum integer
 * @param {number} max The maximum integer
 * @returns {number} A random integer between the `min` and `max` parameters (inclusive)
 */
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

/** @type {import("@minecraft/server").BlockCustomComponent} */
const BlockGrowableComponent = {
    onRandomTick({ block }, { params }) {
        const minLightLevel = params.min_light_level;

        const lightLevel = block.getLightLevel();
        if (lightLevel < minLightLevel) return;

        const growthState = params.growth_state;
        const growthChance = params.growth_chance / 100;
        let maxGrowth = params.max_growth;

        if (Math.random() > growthChance) return;

        const growth = block.permutation.getState(growthState);

        //Tomatoes plant
        const blockAbove = block.above(1);
        const blockBelow = block.below(1);
        if (block.typeId == "farmersdelight:tomato_seeds") {

            // console.warn(growth)

            if (blockBelow.typeId == "farmersdelight:tomato_seeds" &&
                blockBelow.below().typeId == "farmersdelight:tomato_seeds") {
                //No crecer mas para arriba
            }

            else if (blockAbove.typeId == "farmersdelight:rope" && growth == 7) {
                blockAbove.dimension.runCommand(`setblock ${blockAbove.location.x} ${blockAbove.location.y} ${blockAbove.location.z} farmersdelight:tomato_seeds["farmersdelight:rope"=true,"wiki:growth"=4]`)
            }
        }

        if (growth >= maxGrowth) return;


        if (blockBelow && blockBelow.typeId === "farmersdelight:rich_soil_farmland") {
            const increasedGrowth = Math.min(growth + Math.floor(Math.random() * 3) + 1, maxGrowth);
            block.setPermutation(block.permutation.withState(growthState, increasedGrowth));
            block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
            return;
        }

        //////RICE
        //Si es farmersdelight:rice y el crecimiento es 4
        if (block.typeId === "farmersdelight:rice" && growth === 4) {
            block.above(1).setType("farmersdelight:rice_collision");
        }

        // Special case for farmersdelight:rice
        if (block.typeId === "farmersdelight:rice") {
            const blockAbove = block.above(1);
            //Si el bloque superior es rice_collision, pasarle el  valor de "wiki:growth"
            if (blockAbove && blockAbove.typeId === "farmersdelight:rice_collision") {
                blockAbove.setPermutation(blockAbove.permutation.withState("wiki:growth", growth + 1));
            }
            if (blockAbove && (blockAbove.typeId !== "minecraft:air" && blockAbove.typeId !== "farmersdelight:rice_collision") && growth >= 3) {
                // maxGrowth = Math.min(maxGrowth, 3);
                return
            }
        }
        block.setPermutation(block.permutation.withState(growthState, Math.min(growth + 1, maxGrowth)));
    },
    onPlayerInteract({ block, dimension, player }, { params }) {
        const growthState = params.growth_state;
        const maxGrowth = params.max_growth;

        if (!player) return;

        if (block.typeId === "farmersdelight:tomato_seeds" && block.permutation.getState(growthState) === 7) {
            block.dimension.runCommand(`loot spawn ${block.x} ${block.y} ${block.z} loot "tomatoes_ready"`);
            block.dimension.playSound("block.sweet_berry_bush.pick", block.center());
            block.setPermutation(block.permutation.withState(growthState, 4));
            return;
        }

        const equippable = player.getComponent("minecraft:equippable");
        if (!equippable) return;

        const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
        const hasBoneMeal = mainhand.hasItem() && mainhand.typeId === "minecraft:bone_meal";

        if (!hasBoneMeal) return;

        if (player.getGameMode() === GameMode.Creative) {
            // Grow crop fully
            block.setPermutation(block.permutation.withState(growthState, maxGrowth));
        } else {
            let growth = block.permutation.getState(growthState);

            // Add random amount of growth
            growth += randomInt(1, maxGrowth - growth);
            block.setPermutation(block.permutation.withState(growthState, growth));

            // Decrement stack
            if (mainhand.amount > 1) mainhand.amount--;
            else mainhand.setItem(undefined);
        }

        // Play effects
        const effectLocation = block.center();
        dimension.playSound("item.bone_meal.use", effectLocation);
        dimension.spawnParticle("minecraft:crop_growth_emitter", effectLocation);
    },
    onPlayerBreak: result => {
        console.warn()
        if (result.brokenBlockPermutation.type.id == "farmersdelight:tomato_seeds" &&
            result.brokenBlockPermutation.getState("farmersdelight:rope")
        ) {
            result.block.dimension.spawnItem(new ItemStack("farmersdelight:rope", 1), result.block.center())
        }
    }
};

system.beforeEvents.startup.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent("wiki:growable", BlockGrowableComponent);

    blockComponentRegistry.registerCustomComponent("wiki:rice", {
        onPlayerBreak: ({ block, brokenBlockPermutation }) => {

            if (brokenBlockPermutation.type.id === "farmersdelight:rice_collision") {
                block.dimension.runCommand(`setblock ${block.x} ${block.y - 1} ${block.z} farmersdelight:rice["wiki:growth"=4] replace`)
                block.below(1).setPermutation(block.below(1).permutation.withState("wiki:growth", 4));

            }
            else {
                if (block.above(1).typeId === "farmersdelight:rice_collision") {
                    block.above(1).setType("minecraft:air");
                }
            }

            //Si es farmersdelight:rice y el crecimiento es 7
            // if (brokenBlockPermutation.getState("wiki:growth") === 7) {
            //     block.setType("farmersdelight:rice");
            //     block.setPermutation(brokenBlockPermutation.withState("wiki:growth", 3));
            //     block.setWaterlogged(true);
            // }
        },
        beforeOnPlayerPlace: result => {
            if (result.block.typeId != "minecraft:water" && result.permutationToPlace.type.id == "farmersdelight:rice") {
                result.cancel = true;
                system.run(() => {
                    result.player.onScreenDisplay.setActionBar({ "rawtext": [{ "translate": "farmersdelight:rice_plant_not_water" }] })
                })
            }
            else if (result.block.typeId != "minecraft:water" || result.block.above().typeId != "minecraft:air") {
                result.cancel = true;
            }
        }
    });
});