var __decorate=this&&this.__decorate||function(t,e,i,a){var s,r=arguments.length,o=r<3?e:null===a?a=Object.getOwnPropertyDescriptor(e,i):a;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,a);else for(var n=t.length-1;n>=0;n--)(s=t[n])&&(o=(r<3?s(o):r>3?s(e,i,o):s(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},__awaiter=this&&this.__awaiter||function(t,e,i,a){return new(i||(i=Promise))(function(s,r){function o(t){try{l(a.next(t))}catch(t){r(t)}}function n(t){try{l(a.throw(t))}catch(t){r(t)}}function l(t){var e;t.done?s(t.value):((e=t.value)instanceof i?e:new i(function(t){t(e)})).then(o,n)}l((a=a.apply(t,e||[])).next())})};import{css as t,html as e,LitElement as i,unsafeCSS as a}from"lit";import{customElement as s,property as r,state as o,query as n}from"lit/decorators.js";import{i18next as l}from"@openremote/or-translate";import{AssetModelUtil as d}from"@openremote/model";import{DefaultColor3 as h,DefaultColor4 as u,manager as p,Util as m}from"@openremote/core";import{isAxiosError as c}from"@openremote/rest";import{Chart as v,LineController as f,LineElement as b,PointElement as g,LinearScale as w,TimeSeriesScale as y,Title as _}from"chart.js";import"chartjs-adapter-moment";import{InputType as x}from"@openremote/or-mwc-components/or-mwc-input";import{getAssetDescriptorIconTemplate as A}from"@openremote/or-icon";import"@openremote/or-mwc-components/or-mwc-dialog";import"@openremote/or-attribute-picker";import C from"moment";import{OrAssetTreeSelectionEvent as O}from"@openremote/or-asset-tree";import{OrMwcDialog as V,showDialog as S}from"@openremote/or-mwc-components/or-mwc-dialog";import{OrAssetAttributePicker as D,OrAssetAttributePickerPickedEvent as $}from"@openremote/or-attribute-picker";import{getContentWithMenuTemplate as T}from"@openremote/or-mwc-components/or-mwc-menu";import{when as z}from"lit/directives/when.js";import{debounce as M}from"lodash";v.register(f,b,g,w,_,y);let style=t`
    
    :host {
        --internal-or-attribute-history-graph-line-color: var(--or-attribute-history-graph-line-color, var(--or-app-color4, ${a(u)}));       
        width: 100%;
    }
    
    :host([hidden]) {
        display: none;
    }
    
    .panel {
        position: relative;
        height: 100%;
    }
    .panel.panel-empty {
        display: flex;
    }
    .panel.panel-empty .panel-content-wrapper {
        align-items: center;
        width: 100%;
    }
    .panel.panel-empty .panel-content {
        align-items: center;
        justify-content: center;
        flex-direction: column;
    }
    
    .panel-content-wrapper {
        height: 100%;
        display: flex;
        flex-direction: column;
    }
        
    .panel-title {
        display: flex;
        align-items: center;
        /*margin: -15px -15px 0 0;*/ /* compensate for the click-space of the plusminus button */
        font-weight: bolder;
        line-height: 1em;
        color: var(--internal-or-asset-viewer-title-text-color);
        flex: 0 0 auto;
    }
    
    .panel-title-text {
        flex: 1;
        text-transform: uppercase;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }
    
    .panel-content {
        display: flex;
        flex-direction: column;
        width: 100%;
        flex: 1;
    }
    
    .mainvalue-wrapper {
        width: 100%;
        display: flex;
        flex: 0 0 60px;
        align-items: center;
        justify-content: center;
    }
    
    .graph-wrapper {
        width: 100%;
        display: flex;
        flex: 1;
        align-items: center;
    }
    
    .main-number {   
        color: var(--internal-or-asset-viewer-title-text-color);
        font-size: 42px;
    }
    
    .main-number-icon {   
        font-size: 24px;
        margin-right: 10px;
        display: flex;
    }
    
    .main-number-unit {
        font-size: 42px;
        color: var(--internal-or-asset-viewer-title-text-color);
        font-weight: 200;
        margin-left: 5px;
    }
    
    .main-number.xs, .main-number-unit.xs {
        font-size: 18px;
    }
    .main-number.s, .main-number-unit.s {
        font-size: 24px;
    }
    .main-number.m, .main-number-unit.m {
        font-size: 30px;
    }
    .main-number.l, .main-number-unit.l {
        font-size: 36px;
    }
    .main-number.xl, .main-number-unit.xl {
        font-size: 42px;
    }
    
    .chart-wrapper {
        flex: 1 1 auto;
        width: 65%;
        height: 75%;
    }
    .controls-wrapper {
        flex: 0 0 80px;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: end;
        place-content: space-between;
    }
    
    .delta-wrapper {
        /*flex: 0 0 50px;*/
        text-align: right;
        
        /*position: absolute;*/
        /*right: var(--internal-or-asset-viewer-panel-padding);*/
    }
    
    .date-range-wrapper {
        flex: 1;
        display: flex;
        justify-content: space-between;
    }
    
    .period-selector {
        
    }
    
    .delta {
        color: var(--or-app-color3, ${a(h)});
        font-weight: bold;
    }
`,OrAttributeCard=class extends i{static get styles(){return[style]}constructor(){super(),this.assets=[],this.assetAttributes=[],this.data=void 0,this.mainValueDecimals=2,this.mainValueSize="m",this.delta=void 0,this.deltaPlus="",this.deltaFormat="absolute",this.showControls=!0,this.hideAttributePicker=!1,this.showTitle=!0,this._loading=!1,this.period="day"}connectedCallback(){super.connectedCallback(),this._style=window.getComputedStyle(this)}disconnectedCallback(){super.disconnectedCallback(),this._cleanup()}firstUpdated(){this.loadSettings()}updated(t){t.has("realm")&&void 0!=t.get("realm")&&(this.assets=[],this.loadSettings()),(t.has("period")||t.has("compareTimestamp")||t.has("timestamp")||t.has("assetAttributes")||t.has("realm"))&&(this.data=void 0,this._chart&&(this._chart.destroy(),this._chart=void 0),this.loadData()),this.data&&0!==this.data.length&&(this._chart?t.has("data")&&(this._chart.data.datasets[0].data=this.data.filter(t=>null!=t.y),this._chart.update(),this.delta=this.getFormattedDelta(this.getFirstKnownMeasurement(this.data),this.getLastKnownMeasurement(this.data))):this._chart=new v(this._chartElem.getContext("2d"),{type:"line",data:{datasets:[{data:this.data.filter(t=>null!=t.y),tension:.1,spanGaps:!0,backgroundColor:"transparent",borderColor:this._style.getPropertyValue("--internal-or-attribute-history-graph-line-color"),pointBorderColor:"transparent"}]},options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{displayColors:!1,callbacks:{title:t=>"",footer:()=>""}}},scales:{y:{display:!1},x:{type:"time",min:this._startOfPeriod,max:this._endOfPeriod,display:!1}}}}),(t.has("mainValue")||t.has("mainValueDecimals"))&&(this.formattedMainValue=this.getFormattedValue(this.mainValue)),t.has("delta")&&(this.deltaPlus=this.delta&&this.delta.val>0?"+":""))}shouldHideAttributePicker(){return this.hideAttributePicker&&"true"==this.hideAttributePicker.toString()}shouldShowControls(){return this.showControls&&"true"==this.showControls.toString()}shouldShowTitle(){return this.showTitle&&"true"==this.showTitle.toString()}render(){return this._error||this.assets&&this.assetAttributes&&0!==this.assetAttributes.length?(this.updateComplete.then(()=>{this.resizeObserver=new ResizeObserver(M(t=>{let e=t[0].devicePixelContentBoxSize[0].inlineSize;this.setLabelSizeByWidth(e)},200)),this.resizeObserver.observe(this.shadowRoot.querySelector(".graph-wrapper"))}),e`
            <div class="panel" id="attribute-card">
                <div class="panel-content-wrapper">
                    <div class="panel-title">
                        ${this.shouldShowTitle()?e`<span class="panel-title-text">${this.assets[0].name+" - "+l.t(this.assetAttributes[0][1].name)}</span>`:void 0}
                        ${this.shouldShowTitle()?T(e`
                            <or-mwc-input icon="dots-vertical" type="button"></or-mwc-input>
                        `,[{text:l.t("editAttribute"),value:"editAttribute"},{text:l.t("editDelta"),value:"editDelta"},{text:l.t("editCurrentValue"),value:"editCurrentValue"},{text:l.t("delete"),value:"delete"}],void 0,t=>this.handleMenuSelect(t)):void 0}
                    </div>
                    <div class="panel-content">
                        <div class="mainvalue-wrapper">
                            ${z(!this._loading,()=>e`
                                <span class="main-number-icon">${this.assets&&1===this.assets.length?A(d.getAssetDescriptor(this.assets[0].type)):""}</span>
                                <span class="main-number ${this.mainValueSize}">${this.formattedMainValue?this.formattedMainValue.value:""}</span>
                                <span class="main-number-unit ${this.mainValueSize}">${this.formattedMainValue?this.formattedMainValue.unit:""}</span>      
                            `)}
                        </div>
                        <div class="graph-wrapper">
                            
                            ${z(this._error,()=>e`
                                <div style="flex: 0 0 80px;"></div>
                                <or-translate .value="${this._error}" style="flex: 1; text-align: center;"></or-translate>
                            `,()=>e`
                                <div class="chart-wrapper">
                                    ${z(this._loading,()=>e`
                                        <or-loading-indicator></or-loading-indicator>
                                    `,()=>e`
                                        <canvas id="chart"></canvas>
                                    `)}
                                </div>
                            `)}

                            <div class="controls-wrapper">
                                <div class="delta-wrapper">
                                    <span class="delta">${this.delta?this.deltaPlus+(void 0!==this.delta.val&&null!==this.delta.val?this.delta.val:"")+(this.delta.unit||""):""}</span>
                                </div>
                                ${this.shouldShowControls()?e`
                                    <div class="period-selector-wrapper">
                                        ${T(e`<or-mwc-input class="period-selector" .type="${x.BUTTON}" label="${this.period?this.period:"-"}"></or-mwc-input>`,[{value:"hour",text:"hour"},{value:"day",text:"day"},{value:"week",text:"week"},{value:"month",text:"month"},{value:"year",text:"year"}].map(t=>(t.text=l.t(t.value),t)),this.period,t=>this._setPeriodOption(t),void 0,!1,!0,!1,!1,"kpi-menu-id",!0)}
                                    </div>
                                `:e`
                                    <or-mwc-input class="period-selector" .type="${x.BUTTON}" disabled .label="${l.t(this.period?this.period:"-")}"></or-mwc-input>
                                `}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `):e`
                <div class="panel panel-empty">
                    <div class="panel-content-wrapper">
                        <div class="panel-content">
                            ${!this.shouldHideAttributePicker()?e`
                                <or-mwc-input class="button" .type="${x.BUTTON}" label="selectAttribute" icon="plus" @or-mwc-input-changed="${()=>this._openDialog("editAttribute")}"></or-mwc-input>
                            `:e`
                                <span style="text-align: center;">${l.t("noAttributeConnected")}</span>
                            `}
                        </div>
                    </div>
                </div>
            `}_openDialog(t){let i;switch(t){case"editDelta":case"editCurrentValue":(i=new V().setHeading(l.t(t)).setDismissAction(null).setContent("editDelta"===t?e`
                                <or-mwc-input id="delta-mode-picker" value="${this.deltaFormat}" @or-mwc-input-changed="${t=>{this.deltaFormat=t.detail.value,this.saveSettings()}}" .type="${x.LIST}" .options="${[["percentage","Percentage"],["absolute","Absolute"]]}"></or-mwc-input>                
                            `:e`
                                <or-mwc-input id="current-value-decimals" .label="${l.t("decimals")}" value="${this.mainValueDecimals}" .type="${x.TEXT}"></or-mwc-input>
                            `).setActions([{actionName:"cancel",content:e`<or-mwc-input class="button" .type="${x.BUTTON}" label="cancel"></or-mwc-input>`,action:()=>{}},{actionName:"yes",default:!0,content:e`<or-mwc-input class="button" .type="${x.BUTTON}" label="ok" data-mdc-dialog-action="yes"></or-mwc-input>`,action:()=>{if("editDelta"===t)this.delta=this.data?this.getFormattedDelta(this.getFirstKnownMeasurement(this.data),this.getLastKnownMeasurement(this.data)):void 0;else if(i&&i.shadowRoot&&i.shadowRoot.getElementById("current-value-decimals")){let t=parseInt(i.shadowRoot.getElementById("current-value-decimals").value,10);t<0?this.mainValueDecimals=0:t>10?this.mainValueDecimals=10:this.mainValueDecimals=t,this.formattedMainValue=this.getFormattedValue(this.mainValue),this.saveSettings()}}}])).addEventListener(O.NAME,t=>__awaiter(this,void 0,void 0,function*(){let e=t.detail&&t.detail.newNodes.length>0?t.detail.newNodes[0]:void 0;if(e){let t=yield p.events.sendEventWithReply({eventType:"read-asset",assetId:e.asset.id});this.asset=t.asset}else this.asset=void 0}));break;default:(i=new D().setHeading(l.t("selectAttribute"))).addEventListener($.NAME,t=>__awaiter(this,void 0,void 0,function*(){let e=t.detail[0];try{let t=yield p.rest.api.AssetResource.get(e.id);this.asset=t.data,this._setAttribute(e.name)}catch(t){console.error("Failed to get assets requested in settings",t)}}))}i&&S(i)}_setAttribute(t){if(this.asset&&t){let e=this.asset.attributes?this.asset.attributes[t]:void 0;this.assets=[this.asset],this.assetAttributes=e?[[0,e]]:[],this.saveSettings()}}_cleanup(){this._chart&&(this._chart.destroy(),this._chart=void 0)}loadSettings(){return __awaiter(this,arguments,void 0,function*(t=!1){this.assetAttributes=[],(!this.period||t)&&(this.period="day"),(!this.deltaFormat||t)&&(this.deltaFormat="absolute"),(!this.mainValueDecimals||t)&&(this.mainValueDecimals=0),this.realm||(this.realm=p.getRealm());let e=(yield p.console.retrieveData("OrChartConfig"))||[];if(Array.isArray(e)||(e=[e]),0===e.length||!this.panelName)return;let i=window.location.hash,a=e.find(t=>t.realm===this.realm),s=a&&a.views&&a.views[i]?a.views[i][this.panelName]:void 0;if(!s)return;if(!s.attributeRefs){delete a.views[i][this.panelName];let t=[...e.filter(t=>t.realm!==this.realm),a];p.console.storeData("OrChartConfig",t);return}let r=s.attributeRefs.map(t=>t.id);if(0!==r.length&&(this._loading=!0,!r.every(t=>!!this.assets.find(e=>e.id===t)))){try{let t=(yield p.rest.api.AssetResource.queryAssets({ids:r})).data||[];s.attributeRefs=s.attributeRefs.filter(e=>!!t.find(t=>t.id===e.id&&t.attributes&&t.attributes.hasOwnProperty(e.name))),e=[...e.filter(t=>t.realm!==this.realm),a],p.console.storeData("OrChartConfig",e),this.assets=t.filter(t=>s.attributeRefs.find(e=>e.id===t.id))}catch(t){console.error("Failed to get assets requested in settings",t)}this._loading=!1,this.assets&&this.assets.length>0&&(this.assetAttributes=s.attributeRefs.map(t=>{let e=this.assets.findIndex(e=>e.id===t.id),i=e>=0?this.assets[e]:void 0;return i&&i.attributes?[e,i.attributes[t.name]]:void 0}).filter(t=>!!t),this.period=s.period||"day",this.mainValueDecimals=s.decimals||0,this.deltaFormat=s.deltaFormat||"absolute")}})}saveSettings(){return __awaiter(this,void 0,void 0,function*(){if(!this.panelName)return;let t=window.location.hash,e=(yield p.console.retrieveData("OrChartConfig"))||[],i=e.find(t=>t.realm===this.realm);i||(i={realm:this.realm,views:{}}),i.views[t]||(i.views[t]={}),this.assets&&this.assetAttributes&&0!==this.assets.length&&0!==this.assetAttributes.length?(i.realm=this.realm,i.views[t][this.panelName]={attributeRefs:this.assetAttributes.map(([t,e])=>{let i=this.assets[t];return i?{id:i.id,name:e.name}:void 0}).filter(t=>!!t),period:this.period,deltaFormat:this.deltaFormat,decimals:this.mainValueDecimals}):delete i.views[t][this.panelName],e=[...e.filter(t=>t.realm!==this.realm),i],p.console.storeData("OrChartConfig",e)})}loadData(){return __awaiter(this,void 0,void 0,function*(){var t;if(this.data||!this.assetAttributes||!this.assets||0===this.assets.length||0===this.assetAttributes.length||!this.period)return;this._dataAbortController&&(this._dataAbortController.abort("Data request overridden"),delete this._dataAbortController),this._loading=!0;let e="HOUR";switch(this.period){case"hour":e="MINUTE";break;case"day":case"week":e="HOUR";break;case"month":e="DAY";break;case"year":e="MONTH"}e.toLowerCase(),this._startOfPeriod=C().subtract(1,this.period).toDate().getTime(),this._endOfPeriod=C().toDate().getTime();let i=this.assets[0].id,a=this.assetAttributes[0][1].name;this._dataAbortController=new AbortController;try{let t=yield p.rest.api.AssetDatapointResource.getDatapoints(i,a,{type:"lttb",fromTimestamp:this._startOfPeriod,toTimestamp:this._endOfPeriod,amountOfPoints:20},{signal:this._dataAbortController.signal});this._loading=!1,200===t.status&&(this.data=t.data,this.delta=this.getFormattedDelta(this.getFirstKnownMeasurement(this.data),this.getLastKnownMeasurement(this.data)),this.deltaPlus=this.delta&&this.delta.val>0?"+":"",this._error=void 0)}catch(e){if(console.error(e),(null==e?void 0:e.message)==="canceled")return;if(this._loading=!1,c(e)){if(e.message.includes("timeout")){this._error="noAttributeDataTimeout";return}else if((null==(t=e.response)?void 0:t.status)===413){this._error="datapointRequestTooLarge";return}}this._error="couldNotRetrieveAttribute"}finally{this.mainValue=void 0,this.formattedMainValue=void 0;let t=yield p.events.sendEventWithReply({eventType:"read-asset-attribute",ref:{id:i,name:a}});this.mainValue=t.value,this.formattedMainValue=this.getFormattedValue(this.mainValue)}})}getTotalValue(t){return t.reduce((t,e)=>e.y?t+Math.round(e.y):t,0)}getHighestValue(t){return Math.max.apply(Math,t.map(t=>t.y||!1))}getFormattedValue(t){if(void 0===t||!this.assets||!this.assetAttributes||0===this.assets.length||0===this.assetAttributes.length)return;let e=this.assetAttributes[0][1],i=+(null==t?void 0:t.toFixed(this.mainValueDecimals)),a=d.getAttributeDescriptor(e.name,this.assets[0].type),s=m.resolveUnits(m.getAttributeUnits(e,a,this.assets[0].type));return(this.setLabelSizeByLength(i.toString()),s)?{value:i,unit:s}:{value:i,unit:""}}getFirstKnownMeasurement(t){for(let e=0;e<=t.length;e++)if(t[e]&&void 0!==t[e].y)return t[e].y;return 0}getLastKnownMeasurement(t){for(let e=t.length-1;e>=0;e--)if(t[e]&&void 0!==t[e].y)return t[e].y;return 0}getFormattedDelta(t,e){if("percentage"===this.deltaFormat)if(!t||!e)return{val:0,unit:"%"};else if(0===e&&0===t)return{val:0,unit:"%"};else return 0===e&&0!==t?{val:100,unit:"%"}:{val:Math.round((e-t)/t*100),unit:"%"};return{val:Math.round(e-t),unit:""}}handleMenuSelect(t){"delete"===t?(this.assets=[],this.assetAttributes=[],this.saveSettings()):this._openDialog(t)}setLabelSizeByLength(t){t.length>=20&&(this.mainValueSize="xs"),t.length<20&&(this.mainValueSize="s"),t.length<15&&(this.mainValueSize="m"),t.length<10&&(this.mainValueSize="l"),t.length<5&&(this.mainValueSize="xl")}setLabelSizeByWidth(t){t<60?this.mainValueSize="s":t<100?this.mainValueSize="m":t<200?this.mainValueSize="l":this.mainValueSize="xl"}_setPeriodOption(t){this.period=t,this.saveSettings()}};__decorate([r()],OrAttributeCard.prototype,"panelName",void 0),__decorate([r({type:Object})],OrAttributeCard.prototype,"assets",void 0),__decorate([r({type:Object})],OrAttributeCard.prototype,"assetAttributes",void 0),__decorate([r()],OrAttributeCard.prototype,"data",void 0),__decorate([r({type:String})],OrAttributeCard.prototype,"realm",void 0),__decorate([r()],OrAttributeCard.prototype,"mainValue",void 0),__decorate([r()],OrAttributeCard.prototype,"mainValueDecimals",void 0),__decorate([r()],OrAttributeCard.prototype,"mainValueSize",void 0),__decorate([r()],OrAttributeCard.prototype,"delta",void 0),__decorate([r()],OrAttributeCard.prototype,"deltaPlus",void 0),__decorate([r()],OrAttributeCard.prototype,"deltaFormat",void 0),__decorate([r()],OrAttributeCard.prototype,"showControls",void 0),__decorate([r()],OrAttributeCard.prototype,"hideAttributePicker",void 0),__decorate([r()],OrAttributeCard.prototype,"showTitle",void 0),__decorate([r()],OrAttributeCard.prototype,"_loading",void 0),__decorate([r()],OrAttributeCard.prototype,"period",void 0),__decorate([o()],OrAttributeCard.prototype,"_error",void 0),__decorate([n("#chart")],OrAttributeCard.prototype,"_chartElem",void 0),OrAttributeCard=__decorate([s("or-attribute-card")],OrAttributeCard);export{OrAttributeCard};