// (C) 2019-2026 GoodData Corporation
import { invariant } from "ts-invariant";
import { isDashboardLayout } from "@gooddata/sdk-model";
import { DashboardLayoutSectionsFacade } from "./sections.js";
/**
 * @alpha
 */
export class DashboardLayoutFacade {
    layout;
    layoutPath;
    sectionsCache;
    constructor(layout, layoutPath) {
        this.layout = layout;
        this.layoutPath = layoutPath;
    }
    /**
     * Creates an instance of DashboardLayoutFacade
     * @param layout - layout to wrap
     * @param layoutPath - path to the layout, undefined for root layout, path to parent layout item this layout resides in.
     */
    static for(layout, layoutPath) {
        invariant(isDashboardLayout(layout), "Provided data must be IDashboardLayout.");
        return new DashboardLayoutFacade(layout, layoutPath);
    }
    sections() {
        if (this.sectionsCache === undefined) {
            this.sectionsCache = DashboardLayoutSectionsFacade.for(this, this.layout.sections, this.layoutPath);
        }
        return this.sectionsCache;
    }
    section(rowIndex) {
        return this.sections().section(rowIndex);
    }
    nestedLayout(path) {
        const [nextPathEntry, ...remainingPath] = path;
        if (nextPathEntry === undefined) {
            return this;
        }
        const parentPath = this.path();
        const pathToPrint = parentPath ? [...parentPath, nextPathEntry] : [nextPathEntry];
        const nestedLayoutWidget = this.section(nextPathEntry.sectionIndex)?.item(nextPathEntry.itemIndex);
        const isNestedLayout = nestedLayoutWidget?.isLayoutItem();
        invariant(isNestedLayout, `Nested layout at path ${JSON.stringify(pathToPrint)} does not exist.`);
        const nestedLayout = nestedLayoutWidget?.widget();
        if (remainingPath && remainingPath.length > 0) {
            return DashboardLayoutFacade.for(nestedLayout, nestedLayoutWidget.index()).nestedLayout(remainingPath);
        }
        return DashboardLayoutFacade.for(nestedLayout, nestedLayoutWidget.index());
    }
    size() {
        return this.layout.size;
    }
    raw() {
        return this.layout;
    }
    path() {
        return this.layoutPath;
    }
}
