import { Block, EquipmentSlot, Player, system } from "@minecraft/server";
import { arrayIncludes, multiClicking, testing } from "../../utils/systemHelper";
import { BlockStateNames } from "../utils/blockConstants";
import { ParticleIds, SoundsIds } from "../../utils/typingConstants";
import { ItemHelper } from "../../items/utils/itemHelper";
import { WorldHelper } from "../../world/utils/worldHelper";

export const CUSTOM_CROPS = {
    _growItemId: "minecraft:bone_meal",
    
    /**
     * Contains information about the custom crops and their max growth state
     * Keys contains the crop block type ids
     * Values contains their corresponding max growth state
     */
    _cropMaxGrowths: {
        "piki_beyondsurvival:black_radish": 5,
        "piki_beyondsurvival:dragon_carrot": 5,
        "piki_beyondsurvival:ulluco": 5,
        "piki_beyondsurvival:magical_golden_carrot": 3,
        "piki_beyondsurvival:magical_golden_potato": 3
    },

    shouldGrow(itemTypeId, blockTypeId, source) {
        if (itemTypeId != this._growItemId) return;
        if (!arrayIncludes(Object.keys(this._cropMaxGrowths), blockTypeId)) return
        if (multiClicking(source)) return
        return true
    },

    /**
     * 
     * @param {Block} block 
     * @param {Player} source 
     */
    growCrop(block, source) {
        system.run(() => {
            const growthState = block.permutation.getState(BlockStateNames.customGrowth)
            const blockId = block.typeId
            const maxGrowth = this._cropMaxGrowths[blockId]
            
            if (growthState >= maxGrowth) return // testing.error("Already in max growth")
            const newPermutation = block.permutation.withState(BlockStateNames.customGrowth, growthState + 1)
            block.setPermutation(newPermutation)
            // testing.success("Set growth to", growthState + 1)

            const {x, y, z} = block.location
            
            source.playSound(SoundsIds.itemBoneMealUse, {location: source.location, volume: 1, pitch: 0.8})
            source.dimension.spawnParticle(ParticleIds.boneMeal, WorldHelper.createNewLocation(x + 0.5, y + 0.5, z + 0.5))
            ItemHelper.clearPlayerItem(source, EquipmentSlot.Mainhand)
        })
    }
}