import { EquipmentSlot, EntityEquippableComponent, GameMode } from '@minecraft/server';
import { itemManager, randomNum, randomWholeNum } from '../sgs_farm_lib';
import * as mc from "@minecraft/server";
import { cropBlocks } from './sgs_farm_cropconfig';

const HARVEST_WITH_SICKLE = "mob.sheep.shear";
const SOUND_OPTIONS = { pitch: 1.0, volume: 5.0, };

export class cropManager {
    static beforeplace(data) {
        const block = data.block;
        const blockID = data.permutationToPlace.type.id;
        const blockdata = cropBlocks.find((f) => f.blockID == blockID);
        if (blockdata == undefined) return;

        if(blockdata.type == "ground")
        {
            if(block.below().hasTag("sgs_farm_planter_half"))
            {
                data.permutationToPlace = mc.BlockPermutation.resolve(data.permutationToPlace.type.id, {'sgs_farm:shifted': 1});
            }
        }      
    }
    
    //tick data
    static tick(block) {
        const data = cropBlocks.find((f) => f.blockID == block.typeId);
        if (data == undefined) return;
        const stage = this.getGrowthStage(block, data);
        if (stage >= data.maxStage) return;
        const num = randomNum(0, data.growChance.denominator);

        if (num > data.growChance.numerator) return;

        if (data.height == 1) {
            block.setPermutation(block.permutation.withState(data.stateID, stage + 1));
        };
        if (data.height == 2) {
            let block_top = block.above(1);
            //grow if top on block is either air or the top block of the crop
            if (block_top.isAir || block_top.typeId == data.blockID + "_top") {
                block.setPermutation(block.permutation.withState(data.stateID, stage + 1));
                block_top.setPermutation(mc.BlockPermutation.resolve(data.blockID + "_top", { "sgs_farm:growth": stage + 1, "sgs_farm:shifted": block.permutation.getState("sgs_farm:shifted") }));
            }
        };

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

        if (stage >= data.maxStage) {
            if (heldItem != undefined && heldItem.typeId == "sgs_farm:sickle_iron") {
                this.sickle(block, data, player, mainhand, heldItem, stage);
            }
            return;
        }
        else {
            if (heldItem != undefined && stage != data.maxStage && heldItem.typeId == "minecraft:bone_meal" && data.bonemealable) {
                this.bonemeal(block, data, player, mainhand, heldItem, stage);
            }
        }
    }

    //interact with sickle
    static sickle(block, data, player, mainhand, heldItem, stage) {
        let setStage = 0;
        player.playSound(HARVEST_WITH_SICKLE, SOUND_OPTIONS);
        block.setPermutation(block.permutation.withState(data.stateID, setStage));
        if (data.height == 2) block.above(1).setPermutation(mc.BlockPermutation.resolve("minecraft:air"));

        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 });
    }

    //interact with bone meal
    static bonemeal(block, data, player, mainhand, heldItem, stage) {
        let setStage = stage + 3;
        if (setStage > data.maxStage) setStage = data.maxStage;
        try {
            block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
        } catch { }
        block.dimension.playSound("item.bone_meal.use", block.center());
        if (data.height == 1)
        {
            block.setPermutation(block.permutation.withState(data.stateID, setStage));
        };
        if (data.height == 2) {
            let block_top = block.above(1);
            //grow if top on block is either air or the top block of the crop
            if (block_top.isAir || block_top.typeId == data.blockID + "_top") {
                block.setPermutation(block.permutation.withState(data.stateID, stage + 1));
                block_top.setPermutation(mc.BlockPermutation.resolve(data.blockID + "_top", { "sgs_farm:growth": stage + 1, "sgs_farm:shifted": block.permutation.getState("sgs_farm:shifted") }));
            }
        };
        if (player.getGameMode() == GameMode.creative) return;
        mainhand.setItem(itemManager.reduceAmount(heldItem, 1));
    }

    static getGrowthStage(block, cropData) {
        return block.permutation.getState(cropData.stateID);
    }
    static destroyAFrame(block, destroyedBlockPermutation) {
        block.setPermutation(mc.BlockPermutation.resolve("sgs_farm:a_frame", { "minecraft:cardinal_direction": destroyedBlockPermutation.getState("minecraft:cardinal_direction") }));
    }

    static destroyPFrame(block, destroyedBlockPermutation) {
        block.setPermutation(mc.BlockPermutation.resolve("sgs_farm:p_frame"));
    }
}
