import rr from "scripts/lib/railroad.js";

class RailroadDiagramManager {
    constructor() {
        this.figures = new Map();
        this.isCurrentlyNarrow = undefined;

        this.diagramBreakpoint = window.matchMedia("(max-width: 450px)");
        this.diagramBreakpoint.addEventListener("change", () => {
            this.updateVisiblity();
        });
    }

    add(svg) {
        const parent = svg.parentElement;
        if (!this.figures.has(parent)) {
            this.figures.set(parent, []);
        }

        this.figures.get(parent).push(svg);

        parent.removeChild(svg);
    }

    updateVisiblity() {
        const isNarrow = this.diagramBreakpoint.matches;

        if (isNarrow === this.isCurrentlyNarrow) {
            return;
        }

        this.isCurrentlyNarrow = isNarrow;

        for (let [figure, svgs] of this.figures.entries()) {
            for (let svg of svgs) {
                const svgHasNarrowClass = svg.classList.contains("narrow");
                if (isNarrow && svgHasNarrowClass)
                    figure.appendChild(svg);
                else if (!isNarrow && !svgHasNarrowClass)
                    figure.appendChild(svg);
                else if (svg.parentElement === figure)
                    figure.removeChild(svg);
            }
        }
    }
}

let railroadDiagramManager = new RailroadDiagramManager();

export function railroadDiagram(builder, elementID, isNarrow) {
    const diagram = builder(rr);
    const svg = diagram.addTo(document.getElementById(elementID));

    if (isNarrow) {
        svg.classList.add("narrow");
    }

    railroadDiagramManager.add(svg);
}

window.addEventListener("DOMContentLoaded", () => {
    railroadDiagramManager.updateVisiblity();
});
