Source: search/Facets.js

import { EventObject } from "../events/EventObject.js";

export { Facets };

/**
 * Handling of defined and selected facets.
 * Listen to the "change" event to add it to the SearchRequest
 * 
 * @author rkoppe <roland.koppe@awi.de>
 * @author rhess <roland.koppe@awi.de>
 * @memberof vef.search
 */
class Facets extends EventObject {

    selectedFacets = [];
    availableFacets = [];

    constructor() {
        // Initialize EventObject
        super({
            "change": [],
            "select": [],
            "deselect": []
        });
    }

    /**
     * Helper method for fixing the path 
     * 
     * @private
     * @param {string} path 
     * @returns {string} path
     */
    fixPath_(path) {
        let i = path.indexOf('\uf749');
        if (i == -1) i = path.indexOf('/');
        path = path.substr(0, i) + '\uf749' + path.substr(i + 1);
        return path;
    }

    /**
     * Sets all available facets.
     *
     * @param {Object} facets
     */
    setAvailableFacets(facets) {
        this.availableFacets = facets;
    }

    /**
     * Selects a facet for restriction.
     *
     * @param {string} path
     * @param {boolean} triggerEvents default=true
     */
    selectFacet(facet, triggerEvents = true) {
        facet.path = this.fixPath_(facet.path);

        if (this.indexOf(facet.path) > -1) return false;
        this.selectedFacets.push(facet);

        if (triggerEvents) {
            this.fire("select", facet);
            this.fire("change", facet);
        }

        return facet;
    }

    /**
     * Removes the facet identified by path from selected facets.
     *
     * @param {string | object} facet facet or path
     * @param {boolean} triggerEvents default=true
     */
    deselectFacet(facet, triggerEvents = true) {
        const path = (typeof facet == "string") ? facet : facet.path;

        const index = this.indexOf(path);
        if (index == -1) return false;
        facet = this.selectedFacets[index];
        this.selectedFacets.splice(index, 1);

        if (triggerEvents) {
            this.fire("deselect", facet);
            this.fire("change", facet);
        }

        return facet;
    }

    /**
     * Returns the index of the facet identified by path from
     * selected facets. If the facet is not selected -1 is returned.
     *
     * @param {string} path
     * @returns {number} index
     */
    indexOf(path) {
        path = this.fixPath_(path);

        for (let i = 0; i < this.selectedFacets.length; ++i) {
            if (this.selectedFacets[i].path == path) {
                return i;
            }
        }
        return -1;
    }

}