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

const WATERING_RADIUS = 1;

export class wateringCanManager {

    static beforeDurabilityDamage(data) {
        mc.world.sendMessage("durability damage")
        data.durabilityDamage = 0;
    }

    static onUseOn(data) {

        const player = data.source
        const item = data.itemStack;
        const cooldown = data.itemStack.getComponent("minecraft:cooldown");
        const durability = data.itemStack.getComponent("minecraft:durability");
        const block = data.block;
        const dimension = block.dimension
        const location = block.location
        const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);

        //if can is "damaged" try to fill up can and trigger a cooldown
        if (durability.damage > 0) {
            let waterblock;
            for (let x = -WATERING_RADIUS; x < WATERING_RADIUS + 1; x++) {
                for (let z = -WATERING_RADIUS; z < WATERING_RADIUS + 1; z++) {
                    const checkBlock = dimension.getBlock({ x: location.x + x, y: location.y, z: location.z + z });
                    if (waterblock == undefined && checkBlock.typeId == "minecraft:water") {
                        waterblock = checkBlock;
                        break;
                    }
                }
            };
            if (waterblock != undefined) {
                block.dimension.playSound("bucket.fill_water", block.center());
                waterblock.setPermutation(mc.BlockPermutation.resolve("minecraft:air"));
                highlightBlock(waterblock);
                cooldown.startCooldown(player);
                mainhand.setItem(itemManager.addDurability(player, item, 10000));
            }
        }

        //if can is heavily "damaged" or on cooldown it can no longer perform a watering action
        if (durability.damage >= (durability.maxDurability - 10)) {
            block.dimension.playSound("hit.copper", block.center());
            return;
        }
        if (cooldown.getCooldownTicksRemaining(player) > 0) return;

        cooldown.startCooldown(player);
        block.dimension.playSound("bucket.empty_water", block.center());

        for (let x = -WATERING_RADIUS; x < WATERING_RADIUS + 1; x++) {
            for (let z = -WATERING_RADIUS; z < WATERING_RADIUS + 1; z++) {
                for (let y = -1; y < 2; y++) {
                    const wateringBlock = dimension.getBlock({ x: location.x + x, y: location.y + y, z: location.z + z });

                    //play splashy particle for fun
                    if (wateringBlock.isAir) wateringBlock.dimension.spawnParticle("sgs_farm:water_splash_instant", wateringBlock.center());
                    
                    //water farmland to max
                    if (wateringBlock.typeId == "minecraft:farmland") {
                        wateringBlock.setPermutation(mc.BlockPermutation.resolve("minecraft:farmland", { 'moisturized_amount': 7 }));
                        highlightBlock(wateringBlock);
                    }

                    //splash water on plants, 25% chance to initiate a +1 growth tick
                    const num = randomWholeNum(0, 3);
                    const cropData = cropsWatering().find((f) => f.blockID == wateringBlock.typeId);
                    if (cropData != undefined) {

                        if (num == 0) wateringGrowthTick(wateringBlock, cropData, wateringBlock.permutation.getState(cropData.stateID));
                        wateringBlock.dimension.spawnParticle("sgs_farm:water_splash_instant", wateringBlock.center());
                    }
                }
            }
        };
        if (player.getGameMode() == mc.GameMode.creative) return;
        mainhand.setItem(itemManager.reduceDurability(player, item, 100));
    }
}

function wateringGrowthTick(block, data, stage) {

    let setStage = stage + 1;
    if (setStage > data.maxStage) setStage = data.maxStage;
    try {
        block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
    } catch { }
    if (data.height == 1) {
        block.setPermutation(block.permutation.withState(data.stateID, setStage));
    };
    if (data.height == 2) {
        let block_top = block.above(1);
        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") }));
        }
    };
}