import * as mc from "@minecraft/server";
import { cropsCombined } from "../crops/sgs_farm_cropconfig";
import { itemManager, randomWholeNum } from "../sgs_farm_lib";

const SEED_PROCESSING = "random.pop";
const SOUND_OPTIONS = { pitch: 1.0, volume: 5.0, };

const grassBlocks = ["minecraft:short_grass", "minecraft:tall_grass", "minecraft:fern", "minecraft:large_fern"];
export const regionalSeeds = [
    {
        id: "sgs_farm:wild_seed",
        region: "default"
    },
    {
        id: "sgs_farm:wild_seed_forest",
        region: "forest"
    },
    {
        id: "sgs_farm:wild_seed_jungle",
        region: "jungle"
    },
    {
        id: "sgs_farm:wild_seed_mangrove",
        region: "swamp"
    },
    {
        id: "sgs_farm:wild_seed_savanna",
        region: "savanna"
    },
    {
        id: "sgs_farm:wild_seed_taiga",
        region: "taiga"
    },
    {
        id: "sgs_farm:wild_seed_plains",
        region: "plains"
    }
]

dropWildSeed();

export class seedhandlerManager {

    static interactProcessor(data) {
        const block = data.block;
        const player = data.player;
        const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
        const heldItem = mainhand.getItem();
        if (heldItem == undefined) return;
        if (!heldItem.hasTag("sgs_farm:wild_seed_variant")) {
            player.onScreenDisplay.setActionBar("§cOnly works with §oCrops & Farms§c Wild Seed Variants");
            return;
        };

        const seedItems = cropsCombined();
        const wildSeedItem = regionalSeeds.find((f) => f.id == heldItem.typeId);
        let wildSeedItemList = [];

        if (wildSeedItem.region == "default") {
            wildSeedItemList = seedItems;
        }
        else {
            seedItems.forEach(element => {
                if (element.region == wildSeedItem.region) {
                    wildSeedItemList.push(element);
                }
            });
        }

        const dropItem = new mc.ItemStack(wildSeedItemList[Math.floor(Math.random() * wildSeedItemList.length)].seedID, 1);
        const { x, y, z } = block.location;
        block.dimension.spawnItem(dropItem, { x: x + 0.5, y: y + 1.0, z: z + 0.5 });

        player.playSound(SEED_PROCESSING, SOUND_OPTIONS);
        block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());

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

    static interactRecycler(data) {
        const block = data.block;
        const player = data.player;

        const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
        const heldItem = mainhand.getItem();
        if (heldItem == undefined) return;

        const seedItems = cropsCombined();
        const seedItem = seedItems.find((f) => f.cropID == heldItem.typeId);
        if (seedItem == undefined) {
            player.onScreenDisplay.setActionBar("§cOnly works with §oCrops & Farms§c Crops");
            //player.sendMessage("§c[Seed Recycler] Only works with §oCrops & Farms§c Crops");
            return;
        }

        if (heldItem.amount < 4) {
            player.onScreenDisplay.setActionBar("§cUse at least 4 Crops");
            //player.sendMessage("§c[Seed Recycler] Use at least 4 Crops");
            return;
        }

        const dropItem = new mc.ItemStack(seedItems[Math.floor(Math.random() * seedItems.length)].seedID, 1);
        const { x, y, z } = block.location;
        block.dimension.spawnItem(dropItem, { x: x + 0.5, y: y + 1.0, z: z + 0.5 });

        player.playSound(SEED_PROCESSING, SOUND_OPTIONS);
        block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());

        if (player.getGameMode() == mc.GameMode.survival) mainhand.setItem(itemManager.reduceAmount(heldItem, 4));
    }
}

function dropWildSeed() {
    //drop wildseed
    mc.world.afterEvents.playerBreakBlock.subscribe((eventData) => {
        const block = eventData.block;
        const permutation = eventData.brokenBlockPermutation;

        if (!grassBlocks.includes(permutation.type.id)) return;
        //if(!permutation.hasTag("plant")) return;

        const regional_seeds = mc.world.scoreboard.getObjective("sgs_farm_settings").getScore("REGIONAL_SEEDS");
        const seed_chance = 100 - mc.world.scoreboard.getObjective("sgs_farm_settings").getScore("SEED_CHANCE");
        const num = randomWholeNum(0, 100);

        if (num > seed_chance && regional_seeds == 0) {
            block.dimension.spawnItem(new mc.ItemStack("sgs_farm:wild_seed", 1), block.center());
            block.dimension.spawnParticle("sgs_farm:harvest_crop", block.center());
        }
        if (num > seed_chance && regional_seeds == 1) {
            block.dimension.spawnEntity("sgs_farm:region_seed", block.center());
        }
    })

    //regional seed callback
    mc.system.afterEvents.scriptEventReceive.subscribe((eventData) => {
        const { id, sourceEntity } = eventData;

        if (id == "sgs_farm:region_seed") {
            if (sourceEntity == undefined) return;

            const biome = sourceEntity.getProperty("sgs_farm:biome");
            //mc.world.sendMessage("regional " + biome);

            const dimension = sourceEntity.dimension;
            const block = dimension.getBlock(sourceEntity.location);
            block.dimension.spawnItem(new mc.ItemStack(regionalSeeds[biome].id, 1), block.center());
            block.dimension.spawnParticle("sgs_farm:harvest_crop", block.center());
            sourceEntity.remove();
        }
    })
}