import { EquipmentSlot, EntityEquippableComponent, GameMode } from '@minecraft/server';
import { getRandomInt, highlightBlock, itemManager } from '../sgs_farm_lib';
import * as mc from "@minecraft/server";

const WILDFLOWER_RADIUS = 5;
export const flowerBlocks = [
    {
        blockID: "sgs_farm:flower_meadow_buttercup",
        itemID: "sgs_farm:flower_meadow_buttercup_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_daisy",
        itemID: "sgs_farm:flower_meadow_daisy_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_forgetmenot",
        itemID: "sgs_farm:flower_meadow_forgetmenot_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_poppy",
        itemID: "sgs_farm:flower_meadow_poppy_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_musk_mallow",
        itemID: "sgs_farm:flower_meadow_musk_mallow_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_oxeye_daisy",
        itemID: "sgs_farm:flower_meadow_oxeye_daisy_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_vipers_bugloss",
        itemID: "sgs_farm:flower_meadow_vipers_bugloss_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_ladys_bedstraw",
        itemID: "sgs_farm:flower_meadow_ladys_bedstraw_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_wild_carrot",
        itemID: "sgs_farm:flower_meadow_wild_carrot_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_grass_s",
        itemID: "sgs_farm:flower_meadow_grass_s_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_grass_m",
        itemID: "sgs_farm:flower_meadow_grass_m_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    },
    {
        blockID: "sgs_farm:flower_meadow_grass_l",
        itemID: "sgs_farm:flower_meadow_grass_l_item",
        stateID: "sgs_farm:flower_sections",
        maxStage: 3,
        bonemealable: true,
        height: 1,
        type: "ground"
    }
]

export const bushBlocks = [
    {
        blockID: "sgs_farm:flower_bush_ivy",
        itemID: "sgs_farm:flower_bush_ivy_item",
        bonemealable: true,
        type: "bush"
    },
    {
        blockID: "sgs_farm:flower_bush_jasmine_carolina",
        itemID: "sgs_farm:flower_bush_jasmine_carolina_item",
        bonemealable: true,
        type: "bush"
    },
    {
        blockID: "sgs_farm:flower_bush_jasmine_pink",
        itemID: "sgs_farm:flower_bush_jasmine_pink_item",
        bonemealable: true,
        type: "bush"
    },
    {
        blockID: "sgs_farm:flower_bush_jasmine_star",
        itemID: "sgs_farm:flower_bush_jasmine_star_item",
        bonemealable: true,
        type: "bush"
    },
    {
        blockID: "sgs_farm:flower_bush_susan",
        itemID: "sgs_farm:flower_bush_susan_item",
        bonemealable: true,
        type: "bush"
    },
    {
        blockID: "sgs_farm:flower_bush_virginia",
        itemID: "sgs_farm:flower_bush_virginia_item",
        bonemealable: true,
        type: "bush"
    },
    {
        blockID: "sgs_farm:flower_bush_wisteria",
        itemID: "sgs_farm:flower_bush_wisteria_item",
        bonemealable: true,
        type: "bush"
    }
]


export class flowerManager {
    static interactFlowerBush(block, player) {
        //get the crop data
        const data = bushBlocks.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.typeId == "minecraft:bone_meal" && data.bonemealable) {

            block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
            block.dimension.playSound("item.bone_meal.use", block.center());
            const dropItem = new mc.ItemStack(data.itemID, 1);
            const { x, y, z } = block.location;
            block.dimension.spawnItem(dropItem, { x: x + 0.5, y: y + 0.5, z: z + 0.5 });

            if (player.getGameMode() == GameMode.creative) return;
            mainhand.setItem(itemManager.reduceAmount(heldItem, 1));
        }
    }

    static interact(block, player) {
        //get the crop data
        const data = flowerBlocks.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);
        //try to use bone meal if the block isn't at its max stage
        if (stage >= data.maxStage) {
            if (heldItem != undefined && heldItem.typeId == "minecraft:bone_meal" && data.bonemealable) {
                const dropItem = new mc.ItemStack(data.itemID, 1);
                const { x, y, z } = block.location;
                block.dimension.spawnItem(dropItem, { x: x + 0.5, y: y + 0.5, z: z + 0.5 });
                return;
            }
        }
        else {
            if (heldItem != undefined && stage != data.maxStage && heldItem.typeId == "minecraft:bone_meal" && data.bonemealable) {
                this.bonemeal(block, data, player, mainhand, heldItem, stage);
            }
            if (heldItem != undefined && stage != data.maxStage && heldItem.typeId == data.itemID && data.bonemealable) {
                this.bonemeal(block, data, player, mainhand, heldItem, stage);
            }
        }
    }
    //interact with bone meal
    static bonemeal(block, data, player, mainhand, heldItem, stage) {
        let setStage = stage + 1;
        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());
        block.setPermutation(block.permutation.withState(data.stateID, setStage));
        if (player.getGameMode() == GameMode.creative) return;
        mainhand.setItem(itemManager.reduceAmount(heldItem, 1));
    }
    static getGrowthStage(block, cropData) {
        //return the block's growth stage
        return block.permutation.getState(cropData.stateID);
    }

    static destroy(data) {
        if (data.player.getGameMode() == GameMode.creative) return;

        const block = data.block;
        const permutation = data.destroyedBlockPermutation;

        const sections = permutation.getState("sgs_farm:flower_sections");
        const blockdata = flowerBlocks.find((f) => f.blockID == permutation.type.id);
        if (blockdata == undefined) return;

        let dropItem = new mc.ItemStack(blockdata.itemID, sections + 1);
        const { x, y, z } = block.location;
        block.dimension.spawnItem(dropItem, { x: x + 0.5, y: y + 0.5, z: z + 0.5 });
    }

    static beforeplace(data) {
        const block = data.block;
        const blockId = data.permutationToPlace.type.id;

        const location = { x: block.location.x - WILDFLOWER_RADIUS, y: block.location.y - 0.5, z: block.location.z - WILDFLOWER_RADIUS };
        const dimension = block.dimension;

        mc.system.runTimeout(() => {
            mc.world.getDimension(dimension.id).spawnParticle("minecraft:crop_growth_emitter", block.center());
            block.dimension.playSound("item.bone_meal.use", block.center());

            for (let i = 0; i < WILDFLOWER_RADIUS * 2; i++) {
                for (let j = 0; j < WILDFLOWER_RADIUS * 2; j++) {
                    for (let k = -2; k < 2; k++) {
                        const flowerblock = dimension.getBlock({ x: location.x + i, y: location.y + k, z: location.z + j });
                        const place = getRandomInt(0, 3)

                        if (flowerblock.hasTag("grass") && flowerblock.above().isAir && place == 0) {
                            flowerblock.above().setPermutation(this.getRandomFlowerPermutation());
                            mc.world.getDimension(dimension.id).spawnParticle("minecraft:crop_growth_emitter", flowerblock.above().center());
                        }
                    }
                }
            };
        }, 0)

        data.permutationToPlace = this.getRandomFlowerPermutation();
    }

    static getRandomFlowerPermutation() {
        const wildflower_bushes = mc.world.scoreboard.getObjective("sgs_farm_settings").getScore("WILDFLOWER_BUSHES");
        let combinedFlowers = flowerBlocks;
        if (wildflower_bushes == 1) combinedFlowers = flowerBlocks.concat(bushBlocks);

        const flowerdata = combinedFlowers[Math.floor(Math.random() * combinedFlowers.length)];
        if (flowerdata.type == "ground") {
            let cardinal = getRandomInt(1, 3);

            if (cardinal == 0) cardinal = "north";
            if (cardinal == 1) cardinal = "east";
            if (cardinal == 2) cardinal = "south";
            if (cardinal == 3) cardinal = "west";

            return mc.BlockPermutation.resolve(flowerdata.blockID, { 'sgs_farm:flower_sections': getRandomInt(1, 3), 'minecraft:cardinal_direction': cardinal });
        }
        if (flowerdata.type == "bush") {
            return mc.BlockPermutation.resolve(flowerdata.blockID);
        }
    }
}
