import * as Helpers from "../helpers";
import jQuery from "jquery";

export { FilterOverlay };

/**
 * Represents an overlay showing the meaning of different link/node colors.
 * Offers the ability to toggle certain types.
 */
class FilterOverlay {
    /**
     * Creates the overlay for a given graph object.
     * @param {Graph} graph The graph object.
     * @param {String} type The selection type. Can be "link" or "node".
     */
    constructor(graph, type = "link") {
        this.graph = graph;
        this.type = type;
        this.filterChangedCallback = (type) => void type;
    }

    /**
     * Creates the overlay based on the edges and nodes of the graph object.
     * Must be called after the graph has been initialized.
     */
    create() {
        const sceneNode = Helpers.getCanvasDivNode();
        const overlayNode = document.createElement("div");
        overlayNode.className = "link-overlay";
        sceneNode.insertBefore(overlayNode, sceneNode.childNodes[2]);

        const classes =
            this.type === "link"
                ? this.graph.getLinkClasses()
                : this.graph.getNodeClasses();
        const chars = Math.max.apply(
            Math,
            classes.map(function (c) {
                return c.length;
            })
        );

        for (const link of classes) {
            const relation = Helpers.createDiv("relation", overlayNode, {
                type: link, // Attach the link type to the relation div object
                innerHTML: "<p>" + link + "</p>",
            });
            jQuery(relation).click((event) => this.toggleVisibility(event));

            const colorStrip = Helpers.createDiv("rel-container", relation);
            colorStrip.style.backgroundColor = this.graph.edgeColors[link];
            colorStrip.style.width = 10 * chars + "px";
        }
    }

    /**
     * Event handler for the click event of the link type divs.
     * Toggles the visibility of certain edge types.
     * @param {MouseEvent} event
     */
    toggleVisibility(event) {
        const target = event.currentTarget;
        if (this.type === "link") {
            this.graph.toggleLinkVisibility(target.type);
        } else {
            this.graph.toggleNodeVisibility(target.type);
        }
        this.filterChangedCallback(target.type);
        if (getComputedStyle(target).opacity == 1.0) {
            target.style.opacity = 0.4;
        } else {
            target.style.opacity = 1.0;
        }
    }
}