import { EquipmentSlot, EntityEquippableComponent, GameMode } from '@minecraft/server';
import { itemManager, randomNum, randomWholeNum } from '../sgs_cake_lib';
import * as mc from "@minecraft/server";
import { barkBlocks} from '../sgs_cake_crop_config';

export class cinnamonManager {
    static beforeplace(data) {
        data.permutationToPlace = mc.BlockPermutation.resolve(data.permutationToPlace.type.id, { 'sgs_cake:player_placed': 1 });
    }

    //tick data
    static tick(block) {
        const data = barkBlocks.find((f) => f.strippedblockID == block.typeId);
        if (data == undefined) return;
        if (block.permutation.getState('sgs_cake:player_placed') == 1) return;
        const stage = this.getGrowthStage(block, data);
        if (stage >= data.maxStage) {
            const logPermutation = mc.BlockPermutation.resolve(data.blockID, {
                'minecraft:facing_direction': block.permutation.getState("minecraft:facing_direction"),
                'sgs_cake:player_placed': block.permutation.getState("sgs_cake:player_placed")
            });
            block.setPermutation(logPermutation);
            return;
        }

        const num = randomNum(0, data.growChance.denominator);
        if (num > data.growChance.numerator) return;
        block.setPermutation(block.permutation.withState(data.stateID, stage + 1));
    }

    static interact(block, player) {
        const data = barkBlocks.find((f) => f.blockID == block.typeId);
        if (data == undefined) return;
        const mainhand = player.getComponent(EntityEquippableComponent.componentId).getEquipmentSlot(EquipmentSlot.Mainhand);
        const heldItem = mainhand.getItem();

        if (heldItem != undefined && heldItem.hasTag("minecraft:is_axe")) {

            const strippedPermutation = mc.BlockPermutation.resolve(data.strippedblockID, {
                'minecraft:facing_direction': block.permutation.getState("minecraft:facing_direction"),
                'sgs_cake:player_placed': block.permutation.getState("sgs_cake:player_placed")
            });

            block.setPermutation(strippedPermutation);
            player.playSound("use.wood", { pitch: 1.0, volume: 1.0, });

            const dropItem = new mc.ItemStack(data.cropID, randomWholeNum(1, 2));
            const { x, y, z } = block.location;
            block.dimension.spawnItem(dropItem, { x: x + 0.5, y: y + 0.5, z: z + 0.5 });

            const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
            if (player.getGameMode() == mc.GameMode.Creative) return;
            mainhand.setItem(itemManager.reduceDurability(player, heldItem, 5));
        }
    }

    static getGrowthStage(block, cropData) {
        return block.permutation.getState(cropData.stateID);
    }
}
