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

export default class eventManager {
    customEventsList = [];
    constructor() {
    };
    
    listenForEvent(event, def) {
        let object = event === "beforeWatchdogTerminate" || event === "scriptEventReceive" ? "system": "world";
        // return mc[object].events[event].subscribe(data => {
        if (event.startsWith("before")) {
            let eventName = event.replaceAll("before","").split("").map((value,index) => {
                return index === 0 ? value.toLowerCase() : value;
            }).join("");
            return mc[object]?.beforeEvents[eventName]?.subscribe(data => {
                return def(data, "minecraft:" + event);
            });
        } else {
            let eventName = event;
            return mc[object]?.afterEvents[eventName]?.subscribe(data => {
                return def(data, "minecraft:" + event);
            });
        }
    }
    
    
    register(eventName, def) {
        this.customEventsList.push({
            event: eventName,
            def: def
        })
    }
    
    listenForCustomEvent(event, def) {
        this.customEventsList.filter(value => event === value.event).forEach(value => {
            return value.def(def);
        })
    }
    
    tick(callback, interval = null) {
        return mc.system.runInterval(callback,interval);
    }
    
}

