var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { css, html } from "lit";
import { customElement, property, query, state } from "lit/decorators.js";
import "@openremote/or-data-viewer";
import { Page, router } from "@openremote/or-app";
import { createSelector } from "reselect";
import { manager } from "@openremote/core";
import "@openremote/or-dashboard-builder";
import { getInsightsRoute } from "../routes";
import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
export function pageInsightsProvider(store, config) {
    return {
        name: "insights",
        routes: [
            "insights",
            "insights/:editMode",
            "insights/:editMode/:id"
        ],
        pageCreator: () => {
            const page = new PageInsights(store);
            if (config)
                page.config = config;
            return page;
        }
    };
}
let PageInsights = class PageInsights extends Page {
    static get styles() {
        // language=CSS
        return css `

            :host {
                overflow: hidden; 
            }
            
            #builder {
                z-index: 0;
                background: transparent;
            }
        `;
    }
    /* ------------------ */
    updated(changedProperties) {
        if (changedProperties.has("_dashboardId")) {
            this._updateRoute();
        }
    }
    get name() {
        return "insights";
    }
    constructor(store) {
        super(store);
        this._editMode = true;
        this._fullscreen = true;
        this._realmSelector = (state) => state.app.realm || manager.displayRealm;
        this.getRealmState = createSelector([this._realmSelector], () => __awaiter(this, void 0, void 0, function* () {
            if (this._dataviewer)
                this._dataviewer.refresh();
            this._updateRoute(true);
            this.requestUpdate();
        }));
        manager.rest.api.UserResource.getCurrent().then((response) => {
            this._userId = response.data.id;
        }).catch((ex) => {
            console.error(ex);
            showSnackbar(undefined, "errorOccurred");
        });
    }
    connectedCallback() {
        super.connectedCallback();
    }
    render() {
        return html `
            <div style="width: 100%;">
                <or-dashboard-builder id="builder" .editMode="${this._editMode}" .fullscreen="${this._fullscreen}" .selectedId="${this._dashboardId}"
                                      .realm="${manager.displayRealm}" .userId="${this._userId}" .readonly="${!manager.hasRole("write:insights" /* ClientRole.WRITE_INSIGHTS */)}"
                                      @selected="${(event) => { var _a; this._dashboardId = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.id; }}"
                                      @editToggle="${(event) => { this._editMode = event.detail; this._fullscreen = true; this._updateRoute(false); }}"
                                      @fullscreenToggle="${(event) => { this._fullscreen = event.detail; }}"
                ></or-dashboard-builder>
            </div>
        `;
    }
    stateChanged(state) {
        // State is only utilised for initial loading
        this.getRealmState(state); // Order is important here!
        this._editMode = (state.app.params && state.app.params.editMode) ? (state.app.params.editMode === "true" && manager.hasRole("write:insights" /* ClientRole.WRITE_INSIGHTS */)) : false;
        this._dashboardId = (state.app.params && state.app.params.id) ? state.app.params.id : undefined;
    }
    _updateRoute(silent = true) {
        // This if condition prevents updating the URL to /insights/false when no edit mode or dashboard is selected.
        // This avoids polluting the browser history and ensures users don't get redirected to Insights on refresh.
        if (this._editMode || this._dashboardId) {
            router.navigate(getInsightsRoute(this._editMode, this._dashboardId), {
                callHooks: !silent,
                callHandler: !silent
            });
        }
    }
};
__decorate([
    property()
], PageInsights.prototype, "config", void 0);
__decorate([
    query("#data-viewer")
], PageInsights.prototype, "_dataviewer", void 0);
__decorate([
    property()
], PageInsights.prototype, "_editMode", void 0);
__decorate([
    property()
], PageInsights.prototype, "_fullscreen", void 0);
__decorate([
    property()
], PageInsights.prototype, "_dashboardId", void 0);
__decorate([
    state()
], PageInsights.prototype, "_userId", void 0);
PageInsights = __decorate([
    customElement("page-insights")
], PageInsights);
export { PageInsights };
//# sourceMappingURL=page-insights.js.map