import * as mc from "@minecraft/server";
import * as lib from '../lib/lib';

const FLORA_RADIUS = 4;

export class manaHarvesterTopManager {
    static beforeplace(data) {
        const block = data.block;

        if (block.below().type.id == "pb_scraft:mana_harvester") {
            lib.highlightBlock(block);
            lib.highlightBlock(block.below());

            block.dimension.playSound("pb_scraft.altar_item_placed", block.location);
        }
    }

    static interact(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.typeId == "pb_scraft:mana_meter") {

            if(block.type.id == "pb_scraft:mana_harvester_scope") player.sendMessage(this.checkScope(block));
            if(block.type.id == "pb_scraft:mana_harvester_flora") player.sendMessage(this.checkFlora(block));
            player.dimension.playSound("pb_scraft.interact_contraption", data.block.location);
            return;
        }

        this.checkCrafting(data, heldItem, player);
    }

    static checkScope(block) {
        let message = "§u[Magic]§r Harvester is only operating at night";

        if (block.below().type.id != "pb_scraft:mana_harvester") {
            message = "§u[Magic]§r Harvester is missing a base block";
            return message;
        }

        const time = mc.world.getTimeOfDay();
        if (time > 12000 && time < 23000) {
            message = "§u[Magic]§r Harvester is generating mana";
            return message;
        }

        return message;
    }

    static checkFlora(block) {
        const dimension = block.dimension;
        let message = "§u[Magic]§r Harvester is missing flowers nearby";

        if(block.below().type.id != "pb_scraft:mana_harvester")
        {
            message = "§u[Magic]§r Harvester is missing a base block";
            return message;
        }

        const location = { x: block.location.x - FLORA_RADIUS, y: block.location.y - 1, z: block.location.z - FLORA_RADIUS };

        let flora_found = 0;
        for (let i = 0; i < FLORA_RADIUS * 2 + 1; i++) {
            for (let j = 0; j < FLORA_RADIUS * 2 + 1; j++) {
                const florablock = dimension.getBlock({ x: location.x + i, y: location.y, z: location.z + j });

                if (florablock.hasTag("fertilize_area")) {
                    lib.highlightBlock(florablock);
                    flora_found++;
                }
            }
        };

        if (flora_found > 0) {
            message = "§u[Magic]§r Harvester is generating mana";
            return message;
        }

        return message;
    }
}
