var __decorate=this&&this.__decorate||function(e,i,t,r){var s,d=arguments.length,o=d<3?i:null===r?r=Object.getOwnPropertyDescriptor(i,t):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,i,t,r);else for(var a=e.length-1;a>=0;a--)(s=e[a])&&(o=(d<3?s(o):d>3?s(i,t,o):s(i,t))||o);return d>3&&o&&Object.defineProperty(i,t,o),o},__awaiter=this&&this.__awaiter||function(e,i,t,r){return new(t||(t=Promise))(function(s,d){function o(e){try{l(r.next(e))}catch(e){d(e)}}function a(e){try{l(r.throw(e))}catch(e){d(e)}}function l(e){var i;e.done?s(e.value):((i=e.value)instanceof t?i:new t(function(e){e(i)})).then(o,a)}l((r=r.apply(e,i||[])).next())})};import e,{DefaultColor4 as i,DefaultColor5 as t}from"@openremote/core";import{css as r,html as s,LitElement as d,unsafeCSS as o}from"lit";import{customElement as a,property as l,state as n}from"lit/decorators.js";import{style as h}from"./style";import"./or-dashboard-widgetcontainer";import{debounce as c}from"lodash";import{getActivePreset as g}from"./index";import{InputType as p}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-components/or-loading-indicator";import{repeat as v}from"lit/directives/repeat.js";import{GridStack as m}from"gridstack";import{showSnackbar as u}from"@openremote/or-mwc-components/or-mwc-snackbar";import{i18next as w}from"@openremote/or-translate";import{when as b}from"lit/directives/when.js";import{cache as y}from"lit/directives/cache.js";import{guard as f}from"lit/directives/guard.js";import{OrDashboardEngine as _}from"./or-dashboard-engine";import{WidgetService as x}from"./service/widget-service";import{OrDashboardWidgetContainer as C}from"./or-dashboard-widgetcontainer";let gridcss=require("gridstack/dist/gridstack.min.css"),extracss=require("gridstack/dist/gridstack-extra.css"),editorStyling=r`
    
    #loadingContainer {
        position: absolute;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    
    #view-options {
        padding: 24px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    /* Margins on view options */
    #fit-btn { margin-right: 10px; }
    #view-preset-select { margin-left: 20px; }
    #width-input { margin-left: 20px; }
    #height-input { margin-left: 10px; }
    #rotate-btn { margin-left: 10px; }
    
    .maingridContainer {
        position: absolute;
        padding-bottom: 32px;
    }
    .maingridContainer__fullscreen {
        width: 100%;
    }
    
    .maingrid {
        border: 3px solid #909090;
        background: #FFFFFF;
        border-radius: 8px;
        overflow-x: hidden;
        overflow-y: scroll;
        padding: 4px;
        z-index: 0;
    }
    .maingrid__fullscreen {
        border: none;
        background: transparent;
        border-radius: 0;
        overflow-x: hidden;
        overflow-y: scroll;
        height: 100% !important; /* To override .maingrid */
        width: 100% !important; /* To override .maingrid */
        padding: 0;
        /*pointer-events: none;*/
        position: relative;
        z-index: 0;
    }
    .maingrid__disabled {
        pointer-events: none;
        opacity: 40%;
    }
    .grid-stack-item-content {
        background: white;
        box-sizing: border-box;
        border: 1px solid var(--or-app-color5, ${o(t)});
        border-radius: 4px;
    }
    .grid-stack > .grid-stack-item > .grid-stack-item-content {
        overflow: visible;
    }
    .grid-stack-item-content__active {
        border: 2px solid var(--or-app-color4, ${o(i)});
        margin: -1px !important; /* to compromise with the extra pixel of border. */
    }
    
    /* Grid lines on the background of the grid */
    .grid-element {
        background-image:
                linear-gradient(90deg, #E0E0E0, transparent 1px),
                linear-gradient(90deg, transparent calc(100% - 1px), #E0E0E0),
                linear-gradient(#E0E0E0, transparent 1px),
                linear-gradient(transparent calc(100% - 1px), #E0E0E0 100%);
    }
`,OrDashboardPreview=class extends d{set template(e){let i=this._template;if(void 0!=i){let t={changedKeys:Object.keys(e).filter(t=>JSON.stringify(e[t])!==JSON.stringify(i[t])),oldValue:i,newValue:e};this._template=JSON.parse(JSON.stringify(e)),this.latestChanges=t,this.requestUpdate("template",i)}else void 0!=e&&(console.debug("Creating a new Dashboard grid..."),this._template=e,this.setupGrid(!1,!1))}get template(){return this._template}constructor(){super(),this.editMode=!1,this.readonly=!0,this.previewZoom=1,this.fullscreen=!0,this.rerenderActive=!1,this.isLoading=!1,this.cachedGridstackCSS=new Map,this.resizeObserverCallback=e=>{requestAnimationFrame(()=>{var i;(null==(i=this.previousObserverEntry)?void 0:i.contentRect.width)+"px"!=e[0].contentRect.width+"px"&&this._onGridResize(),this.previousObserverEntry=e[0]})},this.realm||(this.realm=e.displayRealm),this.availablePreviewSizes||(this.availablePreviewSizes=[{displayName:"4k Television",width:3840,height:2160},{displayName:"Desktop",width:1920,height:1080},{displayName:"Small desktop",width:1280,height:720},{displayName:"Phone",width:360,height:800},{displayName:"Custom"}]),this.previewSize||(this.previewSize=this.availablePreviewSizes[3]),m.registerEngine(_)}static get styles(){return[o(gridcss),o(extracss),editorStyling,h]}shouldUpdate(e){var i,t,r;return e.has("latestChanges")&&(null==(i=this.latestChanges)?void 0:i.changedKeys.length)==0&&JSON.stringify(null==(t=e.get("latestChanges"))?void 0:t.oldValue)==JSON.stringify(null==(r=e.get("latestChanges"))?void 0:r.newValue)&&e.delete("latestChanges"),this.fullscreen&&e.has("previewWidth")&&e.delete("previewWidth"),this.fullscreen&&e.has("previewHeight")&&e.delete("previewHeight"),0!==e.size&&super.shouldUpdate(e)}updated(i){var t,r,s,d,o,a;if(super.updated(i),void 0==this.realm&&(this.realm=e.displayRealm),!this.template&&this.dashboardId?e.rest.api.DashboardResource.get(this.realm,this.dashboardId).then(e=>{this.template=e.data.template}).catch(e=>{console.error(e),u(void 0,"errorOccurred")}):null==this.template&&null==this.dashboardId&&console.warn("Neither the template nor dashboardId attributes have been specified!"),i.has("latestChanges")&&this.latestChanges&&(this.processTemplateChanges(this.latestChanges),this.latestChanges=void 0),i.has("selectedWidget"))if(this.selectedWidget){if(void 0!=i.get("selectedWidget")&&this.dispatchEvent(new CustomEvent("deselected",{detail:i.get("selectedWidget")})),(null==(t=this.grid)?void 0:t.el)!=null){let e=null==(r=this.grid)?void 0:r.getGridItems().find(e=>{var i,t,r;return(null==(i=e.gridstackNode)?void 0:i.id)==(null==(r=null==(t=this.selectedWidget)?void 0:t.gridItem)?void 0:r.id)});null!=e&&this.selectGridItem(e),this.dispatchEvent(new CustomEvent("selected",{detail:this.selectedWidget}))}}else(null==(s=this.grid)?void 0:s.el)!=void 0&&(null==(d=this.grid)?void 0:d.getGridItems())!=null&&this.deselectGridItems(this.grid.getGridItems()),this.dispatchEvent(new CustomEvent("deselected",{detail:i.get("selectedWidget")}));i.has("editMode")&&void 0!=i.get("editMode")&&(console.debug(`Edit mode is now ${this.editMode}. Force recreating grid...`),this.setupGrid(!0,!0)),(i.has("previewWidth")||i.has("previewHeight"))&&(null==(o=this.template)?void 0:o.screenPresets)&&(this.previewSize=null==(a=this.availablePreviewSizes)?void 0:a.find(e=>e.width+"px"==this.previewWidth&&e.height+"px"==this.previewHeight)),i.has("previewSize")&&this.previewSize&&(this.previewWidth=this.previewSize.width+"px",this.previewHeight=this.previewSize.height+"px"),i.has("rerenderActive")&&this.rerenderActive&&(this.rerenderActive=!1)}setupGrid(e){return __awaiter(this,arguments,void 0,function*(e,i=!1){var t,r,s,d,o,a,l,n,h,c,p,v;this.isLoading=!0,yield this.updateComplete;let u=null==(t=this.shadowRoot)?void 0:t.getElementById("gridElement");if(null!=u){e&&null!=this.grid&&(this.grid.destroy(!1),i&&(this.rerenderActive=!0,yield this.updateComplete,yield this.waitUntil(e=>!this.rerenderActive),u=null==(r=this.shadowRoot)?void 0:r.getElementById("gridElement"),this.grid=void 0));let t=this.fullscreen?this.clientWidth:+(null==(s=this.previewWidth)?void 0:s.replace(/\D/g,"")),w=g(t,this.template.screenPresets);if((null==w?void 0:w.scalingPreset)==(null==(d=this.activePreset)?void 0:d.scalingPreset)||e&&i||(e||null==(o=this.grid)||o.destroy(!1),this.rerenderActive=!0,yield this.updateComplete,yield this.waitUntil(e=>!this.rerenderActive),u=null==(a=this.shadowRoot)?void 0:a.getElementById("gridElement"),this.grid=void 0),this.activePreset=w,null==this.grid){let e=null==(l=this.shadowRoot)?void 0:l.querySelector(".maingrid");this.setupResizeObserver(e)}u.style.maxWidth=this.template.maxScreenWidth+"px",this.grid=m.init({acceptWidgets:this.editMode,animate:!0,cellHeight:(null==(n=this.activePreset)?void 0:n.scalingPreset)==="WRAP_TO_SINGLE_COLUMN"?t/((null==(h=this.template)?void 0:h.columns)?this.template.columns/4:2):"initial",column:null==(c=this.template)?void 0:c.columns,disableOneColumnMode:(null==(p=this.activePreset)?void 0:p.scalingPreset)!=="WRAP_TO_SINGLE_COLUMN",oneColumnModeDomSort:!0,draggable:{appendTo:"parent"},float:!0,margin:5,resizable:{handles:"all"},staticGrid:(null==(v=this.activePreset)?void 0:v.scalingPreset)==="WRAP_TO_SINGLE_COLUMN"||!this.editMode,styleInHead:!1},u),u.style.backgroundSize=""+this.grid.cellWidth()+"px "+this.grid.getCellHeight()+"px",u.style.height="100%",u.style.minHeight="100%",this.grid.on("dropped",(e,i,t)=>this.onWidgetDrop(e,i,t)),this.grid.on("change",(e,i)=>{null!=this.template&&null!=this.template.widgets&&(i.forEach(e=>{var i,t;let r=null==(t=null==(i=this.template)?void 0:i.widgets)?void 0:t.find(i=>{var t;return(null==(t=i.gridItem)?void 0:t.id)==e.id});r.gridItem.x=e.x,r.gridItem.y=e.y,r.gridItem.w=e.w,r.gridItem.h=e.h}),this.dispatchEvent(new CustomEvent("changed",{detail:{template:this.template}})))}),this.grid.on("resizestart",e=>{this.latestDragWidgetStart=new Date}),this.grid.on("resizestop",e=>{setTimeout(()=>{this.latestDragWidgetStart=void 0},200)})}this.isLoading=!1})}refreshPreview(){console.debug("Refreshing dashboard preview!"),this.setupGrid(!0,!0)}refreshWidgets(){var e;null==(e=this.grid)||e.getGridItems().forEach(e=>{let i=e.querySelector(C.tagName);i&&i.refreshContent(!1)})}selectGridItem(e){null!=this.grid&&(this.deselectGridItems(this.grid.getGridItems()),e.querySelectorAll(".grid-stack-item-content").forEach(e=>{e.classList.add("grid-stack-item-content__active")}))}deselectGridItem(e){e.querySelectorAll(".grid-stack-item-content").forEach(e=>{e.classList.remove("grid-stack-item-content__active")})}deselectGridItems(e){e.forEach(e=>{this.deselectGridItem(e)})}onGridItemClick(e){var i,t,r,s,d;this.latestDragWidgetStart||(null==(i=this.grid)?void 0:i.opts.staticGrid)||(e?(null==(r=null==(t=this.selectedWidget)?void 0:t.gridItem)?void 0:r.id)!=e.id&&(this.selectedWidget=null==(d=null==(s=this.template)?void 0:s.widgets)?void 0:d.find(i=>{var t;return(null==(t=i.gridItem)?void 0:t.id)==e.id})):this.selectedWidget=void 0)}onFitToScreenClick(){var e;let i=null==(e=this.shadowRoot)?void 0:e.querySelector("#container");if(i){let e=+(.95*i.clientWidth/this.previewWidth.replace("px","")).toFixed(2);this.previewZoom=e>1?1:e}}isPreviewVisible(){var e;return!this.isLoading&&(null==(e=this.activePreset)?void 0:e.scalingPreset)!="BLOCK_DEVICE"}render(){var e,i,t,r,d,o,a,l;try{(null==(e=this.grid)?void 0:e.el)&&(null==(i=this.grid)?void 0:i.getGridItems())&&(null==(t=this.grid)||t.getGridItems().forEach(e=>{var i,t,r;(null==(t=null==(i=this.template)?void 0:i.widgets)?void 0:t.find(i=>i.id==e.id))==void 0&&(null==(r=this.grid)||r.removeWidget(e))}))}catch(e){console.error(e)}let n="Custom",h=null==(d=null==(r=this.template)?void 0:r.screenPresets)?void 0:d.map(e=>e.displayName);return null==h||h.push(n),s`
            <div id="buildingArea" style="display: flex; flex-direction: column; height: 100%; position: relative;" @click="${e=>{"buildingArea"===e.composedPath()[1].id&&this.onGridItemClick(void 0)}}">
                ${this.editMode&&!this.fullscreen?s`
                    <div id="view-options">
                        <or-mwc-input id="fit-btn" type="${p.BUTTON}" icon="fit-to-screen"
                                      @or-mwc-input-changed="${()=>this.onFitToScreenClick()}">
                        </or-mwc-input>
                        <or-mwc-input id="zoom-input" type="${p.NUMBER}" outlined label="${w.t("dashboard.zoomPercent")}" min="25" .value="${100*this.previewZoom}" style="width: 90px"
                                      @or-mwc-input-changed="${c(e=>{this.previewZoom=e.detail.value/100},50)}"
                        ></or-mwc-input>
                        <or-mwc-input id="view-preset-select" type="${p.SELECT}" outlined label="${w.t("dashboard.presetSize")}" style="min-width: 220px;"
                                      .value="${void 0==this.previewSize?n:this.previewSize.displayName}" .options="${null==(o=this.availablePreviewSizes)?void 0:o.map(e=>e.displayName)}"
                                      @or-mwc-input-changed="${e=>{var i;this.previewSize=null==(i=this.availablePreviewSizes)?void 0:i.find(i=>i.displayName==e.detail.value)}}"
                        ></or-mwc-input>
                        <or-mwc-input id="width-input" type="${p.NUMBER}" outlined label="${w.t("width")}" min="100" .value="${null==(a=this.previewWidth)?void 0:a.replace("px","")}" style="width: 90px"
                                      @or-mwc-input-changed="${c(e=>{this.previewWidth=e.detail.value+"px"},550)}"
                        ></or-mwc-input>
                        <or-mwc-input id="height-input" type="${p.NUMBER}" outlined label="${w.t("height")}" min="100" .value="${null==(l=this.previewHeight)?void 0:l.replace("px","")}" style="width: 90px;"
                                      @or-mwc-input-changed="${e=>{this.previewHeight=e.detail.value+"px"}}"
                        ></or-mwc-input>
                        <or-mwc-input id="rotate-btn" type="${p.BUTTON}" icon="screen-rotation"
                                      @or-mwc-input-changed="${()=>{let e=this.previewHeight,i=this.previewWidth;this.previewWidth=e,this.previewHeight=i}}">
                        </or-mwc-input>
                    </div>
                `:void 0}
                ${this.rerenderActive?s`
                    <div id="container" style="justify-content: center; align-items: center;">
                        <span><or-translate value="dashboard.renderingGrid"></or-translate></span>
                    </div>
                `:s`
                    <div id="container" style="justify-content: center; position: relative;">
                        ${b(this.isLoading,()=>s`
                            <div style="position: absolute; z-index: 3; height: 100%; display: flex; align-items: center;">
                                <or-loading-indicator></or-loading-indicator>
                            </div>
                        `,()=>{var e;return s`
                            ${(null==(e=this.activePreset)?void 0:e.scalingPreset)=="BLOCK_DEVICE"?s`
                                <div style="position: absolute; z-index: 3; height: 100%; display: flex; align-items: center;">
                                    <span><or-translate value="dashboard.deviceNotSupported"></or-translate></span>
                                </div>
                            `:void 0}
                        `})}
                        <!-- The grid itself. Will also show during isLoading, but will be invisible through CSS -->
                        <div class="${this.fullscreen?"maingridContainer__fullscreen":"maingridContainer"}" style="${this.isLoading?"visibility: hidden;":""}">
                            <div class="maingrid ${this.fullscreen?"maingrid__fullscreen":void 0}"
                                 style="width: ${this.previewWidth}; height: ${this.previewHeight}; visibility: ${this.isPreviewVisible()?"visible":"hidden"}; zoom: ${this.editMode&&!this.fullscreen?this.previewZoom:"normal"}; ${this.editMode&&!this.fullscreen?"-moz-transform: scale("+this.previewZoom+")":void 0}; transform-origin: top;"
                                 @click="${e=>{"gridElement"==e.composedPath()[0].id&&this.onGridItemClick(void 0)}}">
                                ${f([this.editMode,this.template],()=>{var e;return s`
                                    <!-- Gridstack element on which the Grid will be rendered -->
                                    <div id="gridElement" class="grid-stack ${this.editMode?"grid-element":void 0}" style="margin: auto;">
                                        ${(null==(e=this.template)?void 0:e.widgets)?v(this.template.widgets,e=>e.id,e=>{var i,t,r,d,o,a,l;return s`
                                                    <div class="grid-stack-item" id="${e.id}" gs-id="${null==(i=e.gridItem)?void 0:i.id}" gs-x="${null==(t=e.gridItem)?void 0:t.x}" gs-y="${null==(r=e.gridItem)?void 0:r.y}"
                                                         gs-w="${null==(d=e.gridItem)?void 0:d.w}" gs-h="${null==(o=e.gridItem)?void 0:o.h}" gs-min-w="${null==(a=e.gridItem)?void 0:a.minW}" gs-min-h="${null==(l=e.gridItem)?void 0:l.minH}"
                                                         @click="${()=>{this.onGridItemClick(e.gridItem)}}">
                                                        <div class="grid-stack-item-content" style="display: flex;">
                                                            <or-dashboard-widget-container .widget="${e}" .editMode="${this.editMode}" style="width: 100%; height: auto; border-radius: 4px;"></or-dashboard-widget-container>
                                                        </div>
                                                    </div>
                                                `}):void 0}
                                    </div>
                                `})}
                            </div>
                        </div>
                    </div>
                `}
            </div>
            <style>
                ${y(b(this.isExtraLargeGrid(),()=>this.applyCustomGridstackGridCSS(this.getGridstackColumns(this.grid)?this.getGridstackColumns(this.grid):this.template.columns)))}
            </style>
        `}getGridstackColumns(e){try{return null==e?void 0:e.getColumn()}catch(e){return}}isExtraLargeGrid(){var e;return!!this.grid&&(this.getGridstackColumns(this.grid)&&this.getGridstackColumns(this.grid)>12||!!((null==(e=this.template)?void 0:e.columns)&&this.template.columns>12))}applyCustomGridstackGridCSS(e){if(this.cachedGridstackCSS.has(e))return s`${this.cachedGridstackCSS.get(e).map(e=>e)}`;{let i=[];for(let t=0;t<e+1;t++)i.push(s`
                    <style>
                        .grid-stack > .grid-stack-item[gs-w="${t}"]:not(.ui-draggable-dragging):not(.ui-resizable-resizing) { width: ${100-100/e*(e-t)}% !important; }
                        .grid-stack > .grid-stack-item[gs-x="${t}"]:not(.ui-draggable-dragging):not(.ui-resizable-resizing) { left: ${100-100/e*(e-t)}% !important; }                    
                    </style>
                `);return this.cachedGridstackCSS.set(e,i),s`${i.map(e=>e)}`}}disconnectedCallback(){var e;super.disconnectedCallback(),null==(e=this.resizeObserver)||e.disconnect()}setupResizeObserver(e){var i;return null==(i=this.resizeObserver)||i.disconnect(),this.fullscreen?this.resizeObserver=new ResizeObserver(c(this.resizeObserverCallback,200)):this.resizeObserver=new ResizeObserver(this.resizeObserverCallback),this.resizeObserver.observe(e),this.resizeObserver}_onGridResize(){console.debug("Grid resize detected. Recreating the grid..."),this.setupGrid(!0,!1)}processTemplateChanges(e){var i,t,r;if(1==e.changedKeys.length&&e.changedKeys.includes("columns")&&this.grid){this.grid.column(e.newValue.columns);let r=null==(i=this.shadowRoot)?void 0:i.querySelector(".maingrid"),s=null==(t=this.shadowRoot)?void 0:t.getElementById("gridElement");s.style.backgroundSize=""+this.grid.cellWidth()+"px "+this.grid.getCellHeight()+"px",s.style.height=r.scrollHeight+"px",console.debug("Amount of columns has been changed! Recreating grid..."),this.setupGrid(!0,!1)}else if(e.changedKeys.length>1)console.debug("Multiple changes detected. Force recreating grid..."),this.setupGrid(!0,!0);else if(e.changedKeys.includes("widgets")){if((null==(r=this.grid)?void 0:r.el)!=null){let e=0;this.grid.getGridItems().forEach(i=>{var t;!i.classList.contains("ui-draggable")&&(null==(t=this.grid)||t.makeWidget(i),e++)}),e>0&&(console.debug(`Created ${e} widgets. Updating the grid...`),this.setupGrid(!1,!1))}}else e.changedKeys.includes("screenPresets")&&(console.debug("New template has a different screen preset! Force recreating grid..."),this.setupGrid(!0,!0))}waitUntil(e){let i=t=>{e()?t():setTimeout(e=>i(t),400)};return new Promise(i)}onWidgetDrop(e,i,t){this.grid&&t&&(this.grid.removeWidget(t.el,!0,!1),x.placeNew(t.widgetTypeId,t.x,t.y).then(e=>{this.dispatchEvent(new CustomEvent("created",{detail:e}))}))}};__decorate([l({hasChanged:(e,i)=>JSON.stringify(e)!=JSON.stringify(i)})],OrDashboardPreview.prototype,"template",null),__decorate([l()],OrDashboardPreview.prototype,"dashboardId",void 0),__decorate([l()],OrDashboardPreview.prototype,"realm",void 0),__decorate([l({type:Object})],OrDashboardPreview.prototype,"selectedWidget",void 0),__decorate([l()],OrDashboardPreview.prototype,"editMode",void 0),__decorate([l()],OrDashboardPreview.prototype,"readonly",void 0),__decorate([l()],OrDashboardPreview.prototype,"previewWidth",void 0),__decorate([l()],OrDashboardPreview.prototype,"previewHeight",void 0),__decorate([l()],OrDashboardPreview.prototype,"previewZoom",void 0),__decorate([l()],OrDashboardPreview.prototype,"previewSize",void 0),__decorate([l()],OrDashboardPreview.prototype,"availablePreviewSizes",void 0),__decorate([l()],OrDashboardPreview.prototype,"fullscreen",void 0),__decorate([n()],OrDashboardPreview.prototype,"latestChanges",void 0),__decorate([n()],OrDashboardPreview.prototype,"activePreset",void 0),__decorate([n()],OrDashboardPreview.prototype,"rerenderActive",void 0),__decorate([n()],OrDashboardPreview.prototype,"isLoading",void 0),OrDashboardPreview=__decorate([a("or-dashboard-preview")],OrDashboardPreview);export{OrDashboardPreview};