import { world } from "@minecraft/server";

let properties = [];

export class Database {
    constructor(name) {
        this.name = name;
        
       world.afterEvents.worldLoad.subscribe(() => {
        const getDatabases = world.getDynamicPropertyIds();
        if (getDatabases) {
            getDatabases.forEach(p => {
                const split = p.split(":");
                if (split[0] === this.name) {
                    if (!properties[this.name]) {
                        properties[this.name] = { properties: [p] };
                    } else {
                        properties[this.name].properties.push(p);
                    }
                }
            });
        }

        if (!properties[this.name]) {
            properties[this.name] = { properties: [] };
        }
       })
    }

    set(property, value) {
        world.setDynamicProperty(this.name + ":" + property, JSON.stringify(value));
        if (properties[this.name].properties.includes(this.name + ":" + property)) return;
        properties[this.name].properties.push(this.name + ":" + property);
    }

    get(property) {
        const data = world.getDynamicProperty(this.name + ":" + property);
        return data !== undefined ? JSON.parse(data) : undefined;
    }

    push(property, newObject) {
    let existingData = this.get(property) || [];
    if (!Array.isArray(existingData)) {
        return console.warn(`Cannot push to '${property}' because it is not an array.`);
    }

    const dataSet = new Set(existingData);
    dataSet.add(newObject);

    this.set(property, [...dataSet]);
}

    remove(property, index) {
        let existingArray = this.get(property);
        if (!Array.isArray(existingArray) || index < 0 || index >= existingArray.length) {
            return console.warn(`Invalid index '${index}' for '${property}'.`);
        }

        existingArray.splice(index, 1);
        this.set(property, existingArray);
    }
    
    getAll(property) {
        return this.get(property);
    }

    delete(property) {
        if (properties[this.name].properties.includes(this.name + ":" + property)) {
            world.setDynamicProperty(this.name + ":" + property, undefined);
            properties[this.name].properties = properties[this.name].properties.filter(p => p !== this.name + ":" + property);
        } else {
            console.warn('Property not found');
        }
    }

    clearAll() {
        properties[this.name].properties.forEach(p => world.setDynamicProperty(p, undefined));
        properties[this.name].properties = [];
    }

    clearAllProperties() {
        properties = [];
        world.getDynamicPropertyIds().forEach(d => world.setDynamicProperty(d, undefined));
    }
}
