import * as mc from "@minecraft/server";

const IRRIGATE_BLOCKS = new Map();
const TICK_INTERVAL = 100;

init();

function init() {
    const propertyIds = mc.world.getDynamicPropertyIds();

    for (let index = 0; index < propertyIds.length; index++) {
        const element = propertyIds[index];
        if (element.startsWith("sgs_mwo_sprinkler_")) {
            //mc.world.setDynamicProperty(element, undefined);
            IRRIGATE_BLOCKS.set(element, true);
        }
    }
    mc.system.runInterval(() => {
        for (let key of IRRIGATE_BLOCKS.keys()) {
            update(key)
        }
    }, TICK_INTERVAL);
}

export function add(block) {
    const key = blockToKey(block);
    if (IRRIGATE_BLOCKS.has(key)) return;

    mc.world.setDynamicProperty(key, 0);
    IRRIGATE_BLOCKS.set(key, true);
    block.setPermutation(mc.BlockPermutation.resolve("minecraft:farmland", { 'moisturized_amount': 7 }));
}

export function remove(block) {
    mc.world.setDynamicProperty(blockToKey(block), undefined);
    IRRIGATE_BLOCKS.delete(blockToKey(block));
}

function update(key) {

    const block = keyToBlock(key);
    if(block == undefined) return;  //block is in unloaded chunk

    try {
        if (block.typeId == "minecraft:farmland") {
            block.setPermutation(mc.BlockPermutation.resolve("minecraft:farmland", { 'moisturized_amount': 7 }));
        }
        else remove(block);

    }
    catch (error) {}

    return true;
}


function blockToKey(block) {

    let location = block.location;
    let dimension = block.dimension.id;

    return "sgs_mwo_sprinkler_" + dimension + "_" + location.x + "_" + location.y + "_" + location.z;
}

function keyToBlock(key) {
    const blockdata = key.split("_");
    const block = mc.world.getDimension(blockdata[3]).getBlock({ x: parseInt(blockdata[4]), y: 0 + parseInt(blockdata[5]), z: 0 + parseInt(blockdata[6]) })

    return block;
}