import { world, system, ItemStack, BlockPermutation } from "@minecraft/server";

// Script Events

system.afterEvents.scriptEventReceive.subscribe((e) => {
    switch(e.id) {
        case "conduit:set_property": {
            setProperty(e.sourceEntity, extractData(e));
            break;
        }
        case "conduit:despawn": {
            if(e.sourceEntity != null && e.sourceEntity.isValid() && e.sourceEntity.typeId != "minecraft:player") e.sourceEntity.remove();
            break;
        }
    }
}, { "namespaces": ["conduit"] });


// Internal utilities

function logMembers(obj) {
    world.sendMessage("Members:");
    if(obj == null) {
        world.sendMessage("§8[null]");
        return;
    }
    let prototype = Object.getPrototypeOf(obj);
    while(prototype != null && prototype != Object.prototype && prototype != Array.prototype) {

        world.sendMessage("§7  [" + prototype.constructor.name + "]");
        for(let key of Object.getOwnPropertyNames(prototype)) {
            if(key === "constructor") continue;
            if(typeof(prototype[key]) === "function") {
                world.sendMessage("  - §7" + key + "()");
            } else {
                world.sendMessage("  - §7" + key);
            }
        }

        prototype = Object.getPrototypeOf(prototype);
    }
}

function logError(message) {
    world.sendMessage("§c" + message);
}

function extractData(e) {
    var data;
    try {
        data = JSON.parse(e.message);
    } catch(e) {
        logError(e);
        return;
    }
    return data;
}

// ================================ 
//           SET PROPERTY
// ================================ 

function setProperty(entity, data) {
    if(entity == null || data == null || !entity.isValid()) return;

    let property = data["property"];
    let value = data["value"];
    if(value == null && data.from != null) {
        if(data.from.objective != null) {
            let objective = world.scoreboard.getObjective(data.from.objective);
            if(data.from.name != null) {
                value = objective.getScore(data.from.name);
            } else {
                value = objective.getScore(entity);
            }
            if(value == null) return;
            if(data.from.scale != null) {
                value *= data.from.scale;
            }
        }
    }

    if(typeof(entity.getProperty(property)) == "boolean") {
        value = value != 0;
    }

    entity.setProperty(property, value);
    // world.sendMessage("Set property " + property + " of entity " + entity.nameTag + " to " + value);
}

