/**
 * @module Ontology
 */

export class Ontology {
    #data;

    /**
     * @param {Object} data The parsed ontology object (from JSON)
     */
    set data(data) {
        this.#data = data;
    }

    /**
     * @param {String} id 
     */
    getInstanceById(id) {
        return this.#data.instancesById[id];
    }

    /**
     * @returns {Array<{en: string, it: string}>} The bloody array of label objects
     */
    getInstanceLabels() {
        const data = this.#data;
        const instances = [];
        
        for (const key of Object.keys(data.instancesById)) {
            instances.push(data.instancesById[key]?.label);
        }

        return instances;
    }
}

/**
 * @todo Temporarily returns domains and ontology labels only
 * Traverse an ontology from its JSON description
 * @param {Object} ontologyObject The parsed ontology JSON
 * @returns {Object}
 */
export async function traverseOntology(ontologyObject) {
    //const ontology = await loadOntology(jsonPath);
    const modules = ontologyObject.domains;

    const domains = [];

    for (const module of modules) {
        let tree = [];
        for (const classTree of module.classTrees) {
            traverseClasses(classTree, tree);
        }
        domains.push({
            id: module.label.it ?? module.label.en,
            tree
        });
    }

    return domains;
}

/**
 * 
 * @param {Object} ontologyClass 
 * @param {Array<Object>} tree 
 * @param {Number} depth
 */
function traverseClasses(ontologyClass, tree, depth = 1) {
    const ontologyNode = {
        id: ontologyClass.id,
        label: ontologyClass.label,
        depth,
        children: [],
    };

    tree.push(ontologyNode);

    if (ontologyClass.children && Array.isArray(ontologyClass.children)) {
        for(const child of ontologyClass.children) {
            ontologyNode.children.push(
                traverseClasses(child, tree, depth + 1)
            );
        }
    }
}

/**
 * Load an ontology from its JSON description
 * @param {String} jsonPath The path (URI) of the ontology JSON file
 * @returns {Object}
 */
export async function loadOntology(jsonPath) {
    const ontology = await fetch(jsonPath)
        .then(res => res.json())
        .catch(err => console.error(err));

    return ontology;
}
