var OrChart_1,__decorate=this&&this.__decorate||function(t,e,i,r){var o,a=arguments.length,s=a<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,i,r);else for(var n=t.length-1;n>=0;n--)(o=t[n])&&(s=(a<3?o(s):a>3?o(e,i,s):o(e,i))||s);return a>3&&s&&Object.defineProperty(e,i,s),s},__awaiter=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))(function(o,a){function s(t){try{l(r.next(t))}catch(t){a(t)}}function n(t){try{l(r.throw(t))}catch(t){a(t)}}function l(t){var e;t.done?o(t.value):((e=t.value)instanceof i?e:new i(function(t){t(e)})).then(s,n)}l((r=r.apply(t,e||[])).next())})};import{css as t,html as e,LitElement as i,unsafeCSS as r}from"lit";import{customElement as o,property as a,state as s,query as n}from"lit/decorators.js";import l from"i18next";import{translate as d}from"@openremote/or-translate";import{AssetModelUtil as h}from"@openremote/model";import c,{DefaultColor2 as p,DefaultColor3 as m,DefaultColor4 as u,DefaultColor5 as f,Util as v}from"@openremote/core";import"@openremote/or-asset-tree";import"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-components/or-panel";import"@openremote/or-translate";import*as g from"echarts/core";import{DataZoomComponent as y,GridComponent as b,MarkLineComponent as _,TooltipComponent as w}from"echarts/components";import{LineChart as x}from"echarts/charts";import{CanvasRenderer as O}from"echarts/renderers";import{UniversalTransition as C}from"echarts/features";import{InputType as A}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-components/or-loading-indicator";import $ from"moment";import{OrAssetTreeSelectionEvent as D}from"@openremote/or-asset-tree";import{getAssetDescriptorIconTemplate as P}from"@openremote/or-icon";import{isAxiosError as S}from"@openremote/rest";import{OrAssetAttributePicker as T,OrAssetAttributePickerPickedEvent as E}from"@openremote/or-attribute-picker";import{OrMwcDialog as k,showDialog as L}from"@openremote/or-mwc-components/or-mwc-dialog";import{cache as R}from"lit/directives/cache.js";import{debounce as W}from"lodash";import{getContentWithMenuTemplate as M}from"@openremote/or-mwc-components/or-mwc-menu";import{when as z}from"lit/directives/when.js";import{createRef as N,ref as H}from"lit/directives/ref.js";g.use([b,w,y,_,x,O,C]);export class OrChartEvent extends CustomEvent{constructor(t,e){super(OrChartEvent.NAME,{detail:{value:t,previousValue:e},bubbles:!0,composed:!0})}}OrChartEvent.NAME="or-chart-event";let dialogStyle=require("@material/dialog/dist/mdc.dialog.css"),tableStyle=require("@material/data-table/dist/mdc.data-table.css"),style=t`
    :host {
        
        --internal-or-chart-background-color: var(--or-chart-background-color, var(--or-app-color2, ${r(p)}));
        --internal-or-chart-border-color: var(--or-chart-border-color, rgba(76, 76, 76, 0.6));
        --internal-or-chart-text-color: var(--or-chart-text-color, var(--or-app-color3, ${r(m)}));
        --internal-or-chart-controls-margin: var(--or-chart-controls-margin, 0 0 20px 0);       
        --internal-or-chart-controls-margin-children: var(--or-chart-controls-margin-children, 0 auto 20px auto);            
        --internal-or-chart-graph-fill-color: var(--or-chart-graph-fill-color, var(--or-app-color4, ${r(u)}));       
        --internal-or-chart-graph-fill-opacity: var(--or-chart-graph-fill-opacity, 0.25);       
        --internal-or-chart-graph-line-color: var(--or-chart-graph-line-color, var(--or-app-color4, ${r(u)}));       
        --internal-or-chart-graph-point-color: var(--or-chart-graph-point-color, var(--or-app-color3, ${r(m)}));
        --internal-or-chart-graph-point-border-color: var(--or-chart-graph-point-border-color, var(--or-app-color5, ${r(f)}));
        --internal-or-chart-graph-point-radius: var(--or-chart-graph-point-radius, 4);
        --internal-or-chart-graph-point-hit-radius: var(--or-chart-graph-point-hit-radius, 20);       
        --internal-or-chart-graph-point-border-width: var(--or-chart-graph-point-border-width, 2);
        --internal-or-chart-graph-point-hover-color: var(--or-chart-graph-point-hover-color, var(--or-app-color5, ${r(f)}));       
        --internal-or-chart-graph-point-hover-border-color: var(--or-chart-graph-point-hover-border-color, var(--or-app-color3, ${r(m)}));
        --internal-or-chart-graph-point-hover-radius: var(--or-chart-graph-point-hover-radius, 4);      
        --internal-or-chart-graph-point-hover-border-width: var(--or-chart-graph-point-hover-border-width, 2);
        
        width: 100%;
        display: block; 
    }

    .line-label {
        border-width: 1px;
        border-color: var(--or-app-color3);
        margin-right: 5px;
    }

    .line-label.solid {
        border-style: solid;
    }

    .line-label.dashed {
        background-image: linear-gradient(to bottom, var(--or-app-color3) 50%, white 50%);
        width: 2px;
        border: none;
        background-size: 10px 16px;
        background-repeat: repeat-y;
    }
    
    .button-icon {
        align-self: center;
        padding: 11px 6px;
        cursor: pointer;
    }

    a {
        display: flex;
        cursor: pointer;
        text-decoration: underline;
        font-weight: bold;
        color: var(--or-app-color1);
        --or-icon-width: 12px;
    }

    .mdc-dialog .mdc-dialog__surface {
        min-width: 600px;
        height: calc(100vh - 50%);
    }
    
    :host([hidden]) {
        display: none;
    }
    
    #container {
        display: flex;
        min-width: 0;
        flex-direction: row;
        height: 100%;
        gap: 8px;
    }
       
    #msg {
        height: 100%;
        width: 100%;
        justify-content: center;
        align-items: center;
        text-align: center;
    }
    
    #msg:not([hidden]) {
        display: flex;    
    }
    
    #period-controls {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    #period-dropdown-controls {
        flex: 0;
        display: flex;
    }

    #period-dropdown-controls > *:first-child {
        margin-right: -2px;
    }

    #period-dropdown-controls > *:last-child {
        margin-left: -2px;
    }
    

    #controls {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        flex-direction: column;
        justify-content: center;
    }

    #attribute-list {
        overflow: hidden auto;
        flex: 1 1 50px;
        width: 100%;
        display: flex;
        flex-direction: column;
    }
    .attribute-list-dense {
        flex-wrap: wrap;
    }
    
    .attribute-list-item {
        cursor: pointer;
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 0;
        min-height: 50px;
    }
    .attribute-list-item-dense {
        min-height: 28px;
    }

    .button-clear {
        background: none;
        visibility: hidden;
        color: ${r(f)};
        --or-icon-fill: ${r(f)};
        display: inline-block;
        border: none;
        padding: 0;
        cursor: pointer;
    }

    .attribute-list-item:hover .button-clear {
        visibility: visible;
    }

    .button-clear:hover {
        --or-icon-fill: var(--or-app-color4);
    }
    
    .attribute-list-item-label {
        display: flex;
        flex: 1 1 0;
        line-height: 16px;
        flex-direction: column;
    }

    .attribute-list-item-bullet {
        width: 12px;
        height: 12px;
        border-radius: 7px;
        margin-right: 10px;
    }

    .attribute-list-item .button.delete {
        display: none;
    }

    .attribute-list-item:hover .button.delete {
        display: block;
    }
    
    .dialog-container {
        display: flex;
        flex-direction: row;
        flex: 1 1 0;
    }

    .dialog-container > * {
        flex: 1 1 0;
    }
    
    .dialog-container > or-mwc-input {
        background-color: var(--or-app-color2);
        border-left: 3px solid var(--or-app-color4);
    }

    #chart-container {
        flex: 1 1 0;
        position: relative;
        overflow: hidden;
        gap: 4px;
        /*min-height: 400px;
        max-height: 550px;*/
    }
    #chart-controls {
        padding: 0 8px;
        display: flex;
        flex-direction: column;
    }
    #chart {
        width: 100% !important;
        height: 100%; !important;
    }

    @media screen and (max-width: 769px) {
        .mdc-dialog .mdc-dialog__surface {
            min-width: auto;

            max-width: calc(100vw - 32px);
            max-height: calc(100% - 32px);
        }

        #container {
            flex-direction: column;
        }

        #controls {
            min-width: 100%;
            padding-left: 0;
        }
        #period-controls {
            flex-direction: row;
            justify-content: left;
            align-items: center;
            gap: 8px;
        }
    }
`,OrChart=OrChart_1=class extends d(l)(i){static get styles(){return[t`${r(tableStyle)}`,t`${r(dialogStyle)}`,style]}constructor(){super(),this.assets=[],this.assetAttributes=[],this.attributeColors=[],this.attributeConfig=this._getDefaultAttributeConfig(),this.colors=OrChart_1.DEFAULT_COLORS,this.attributeControls=!0,this.timestampControls=!0,this.stacked=!1,this.showLegend=!0,this.denseLegend=!1,this.showZoomBar=!0,this._loading=!1,this._zoomChanged=!1,this._isCustomWindow=!1,this._tooltipCache=[0,""],this.addEventListener(D.NAME,this._onTreeSelectionChanged)}connectedCallback(){super.connectedCallback(),this._style=window.getComputedStyle(this)}disconnectedCallback(){super.disconnectedCallback(),this._cleanup()}firstUpdated(){this.loadSettings(!1)}updated(t){var e,i,r,o,a,s,n,l,d,h,c,p,m,u,f,v,y,b,_;if(super.updated(t),t.has("realm")&&void 0!=t.get("realm")&&(this.assets=[],this.loadSettings(!0)),(t.has("attributeColors")||t.has("datapointQuery")||t.has("timeframe")||t.has("timePrefixKey")||t.has("timeWindowKey")||t.has("attributeConfig")||t.has("assetAttributes")||t.has("realm")||t.has("dataProvider"))&&(this._data=void 0,this._chart&&(this._toggleChartEventListeners(!1),this._chart.dispose(),this._chart=void 0),this._loadData()),this._data){if(!this._chart){let t=this._style.getPropertyValue("--internal-or-chart-graph-fill-color").trim(),w=Number(this._style.getPropertyValue("--internal-or-chart-graph-fill-opacity").trim());!isNaN(w)&&(t.startsWith("#")&&(4===t.length||7===t.length)?t+=4===t.length?Math.round(255*w).toString(16).substr(0,1):Math.round(255*w).toString(16):t.startsWith("rgb(")&&(t=t.substring(0,t.length-1)+w)),this.chartOptions={animation:!1,grid:{show:!0,backgroundColor:this._style.getPropertyValue("--internal-or-asset-tree-background-color"),borderColor:this._style.getPropertyValue("--internal-or-chart-border-color"),left:10,right:10,top:10,bottom:this.showZoomBar?68:10,containLabel:!0},backgroundColor:this._style.getPropertyValue("--internal-or-asset-tree-background-color"),tooltip:{trigger:"axis",confine:!0,axisPointer:{type:"cross"},formatter:t=>{let e=t[0].axisValue;return e!==this._tooltipCache[0]&&(this._tooltipCache[0]=e,this._tooltipCache[1]=this._getTooltipData(e)),this._tooltipCache[1]}},xAxis:{type:"time",axisLine:{onZero:!1,lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color")}},splitLine:{show:!0},min:this._startOfPeriod,max:this._endOfPeriod,markLine:{data:[{name:"now",xAxis:Date.now()}],silent:!0,lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color")}},axisLabel:{hideOverlap:!0,fontSize:10,formatter:{year:"1-{MMM}-{yyyy}",month:"1-{MMM}-'{yy}",day:"{d}-{MMM}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{d}-{MMM} {HH}:{mm}",none:"{MMM}-{dd} {HH}:{mm}"}}},yAxis:[{type:"value",axisLine:{lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color")}},boundaryGap:["10%","10%"],scale:!0,min:null==(o=null==(r=null==(i=null==(e=this.chartOptions)?void 0:e.options)?void 0:i.scales)?void 0:r.y)?void 0:o.min,max:null==(l=null==(n=null==(s=null==(a=this.chartOptions)?void 0:a.options)?void 0:s.scales)?void 0:n.y)?void 0:l.max,axisLabel:{hideOverlap:!0}},{type:"value",show:(null!=(c=null==(h=null==(d=this.attributeConfig)?void 0:d.rightAxisAttributes)?void 0:h.length)?c:0)>0,axisLine:{lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color")}},boundaryGap:["10%","10%"],scale:!0,min:null==(f=null==(u=null==(m=null==(p=this.chartOptions)?void 0:p.options)?void 0:m.scales)?void 0:u.y1)?void 0:f.min,max:null==(_=null==(b=null==(y=null==(v=this.chartOptions)?void 0:v.options)?void 0:y.scales)?void 0:b.y1)?void 0:_.max,axisLabel:{hideOverlap:!0}}],dataZoom:[{type:"inside",start:0,end:100}],series:[]},this.showZoomBar&&this.chartOptions.dataZoom.push({start:0,end:100,backgroundColor:t,fillerColor:t,dataBackground:{areaStyle:{color:this._style.getPropertyValue("--internal-or-chart-graph-fill-color")}},selectedDataBackground:{areaStyle:{color:this._style.getPropertyValue("--internal-or-chart-graph-fill-color")}},moveHandleStyle:{color:this._style.getPropertyValue("--internal-or-chart-graph-fill-color")},emphasis:{moveHandleStyle:{color:this._style.getPropertyValue("--internal-or-chart-graph-fill-color")},handleLabel:{show:!1}},handleLabel:{show:!1}}),this._chart=g.init(this._chartElem),this._chart.setOption(this.chartOptions),this._toggleChartEventListeners(!0)}t.has("_data")&&this._updateChartData(),this.getUpdateComplete().then(()=>{this.dispatchEvent(new OrChartEvent("rendered"))})}}applyChartResponsiveness(){if(this.shadowRoot){let t=this.shadowRoot.getElementById("container");if(t){let e=t.clientWidth<600;t.style.flexDirection=e?"column":"row";let i=this.shadowRoot.getElementById("controls");i&&(i.style.flexDirection=e?"row":"column");let r=this.shadowRoot.getElementById("period-controls");r&&(r.style.flexDirection=e?"row":"column");let o=this.shadowRoot.getElementById("attribute-list");o&&(o.style.gap=e?"4px 12px":"",o.style.maxHeight=e?"90px":"",o.style.flexFlow=e?"row wrap":"column nowrap",o.style.padding=e?"0":"5px 0"),this.shadowRoot.querySelectorAll(".attribute-list-item").forEach(t=>{t.style.minHeight=e?"0px":"44px",t.style.paddingLeft=e?"":"0",t.children[1].style.flexDirection=e?"row":"column",t.children[1].style.gap=e?"4px":""})}}}render(){let t=this._latestError;return e`
            <div id="container">
                <div id="chart-container" style="opacity: ${this._loading?"0.7":"1"};">
                    ${z(this._loading&&!this._data,()=>e`
                        <div style="position: absolute; height: 100%; width: 100%;">
                            <or-loading-indicator ?overlay="false"></or-loading-indicator>
                        </div>
                    `)}
                    ${z(this._latestError,()=>e`
                        <div style="position: absolute; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;">
                            <or-translate .value="${this._latestError||"errorOccurred"}"></or-translate>
                        </div>
                    `)}
                    <div id="chart" style="visibility: ${t?"hidden":"visible"};"></div>
                </div>
                
                ${this.timestampControls||this.attributeControls||this.showLegend?e`
                    <div id="chart-controls">
                        <div id="controls">
                                ${this.timePrefixKey&&this.timePrefixOptions&&this.timeWindowKey&&this.timeWindowOptions?e`
                                    ${this.timestampControls?e`
                                        <div id="period-controls">
                                            <div id="period-dropdown-controls">
                                                <!-- Time prefix selection -->
                                                ${M(e`<or-mwc-input .type="${A.BUTTON}" label="${this.timeframe?"dashboard.customTimeSpan":this.timePrefixKey.toLowerCase()}"></or-mwc-input>`,this.timePrefixOptions.map(t=>({value:t,text:t.toLowerCase()})),this.timePrefixKey,t=>{this.timeframe=void 0,this.timePrefixKey=t.toString()},void 0,void 0,void 0,!0)}
                                                <!-- Time window selection -->
                                                ${M(e`<or-mwc-input .type="${A.BUTTON}" label="${this._isCustomWindow?"timeframe":this.timeWindowKey.toLowerCase()}"></or-mwc-input>`,Array.from(this.timeWindowOptions.keys()).map(t=>({value:t,text:t.toLowerCase()})),this.timeWindowKey,t=>{this.timeframe=void 0,this.timeWindowKey=t.toString()},void 0,void 0,void 0,!0)}
                                            </div>
                                        </div>
                                        <div style="text-align: center">
                                            <!-- Scroll left button -->
                                            <or-icon class="button button-icon" ?disabled="${t}" icon="chevron-left"
                                                     @click="${()=>{var t,e,i,r;return this._shiftTimeframe(null!=(e=null==(t=this.timeframe)?void 0:t[0])?e:new Date(this._startOfPeriod),null!=(r=null==(i=this.timeframe)?void 0:i[1])?r:new Date(this._endOfPeriod),this.timeWindowKey,"previous")}}"
                                            ></or-icon>
                                            <!-- Scroll right button -->
                                            <or-icon class="button button-icon" ?disabled="${t}" icon="chevron-right"
                                                     @click="${()=>{var t,e,i,r;return this._shiftTimeframe(null!=(e=null==(t=this.timeframe)?void 0:t[0])?e:new Date(this._startOfPeriod),null!=(r=null==(i=this.timeframe)?void 0:i[1])?r:new Date(this._endOfPeriod),this.timeWindowKey,"next")}}"
                                            ></or-icon>
                                            <!-- Button that opens custom time selection or restores to widget setting-->
                                            <or-icon class="button button-icon" ?disabled="${t}" icon="${this.timeframe?"restore":"calendar-clock"}"
                                                     @click="${()=>this.timeframe?(this._isCustomWindow=!1,this.timeframe=void 0):this._openTimeDialog(this._startOfPeriod,this._endOfPeriod)}"
                                            ></or-icon>
                                        </div>
                                    `:e`
                                        <div style = "display: flex; flex-direction: column; align-items: center">
                                            <or-mwc-input .type="${A.BUTTON}" label="${this.timePrefixKey}" disabled></or-mwc-input>
                                            <or-mwc-input .type="${A.BUTTON}" label="${this.timeWindowKey}" disabled></or-mwc-input>
                                        </div>
                                    `}
                                `:void 0}
                            
                            ${this.timeframe?e`
                                <div style="font-size: 12px; display: flex; justify-content: flex-end;">
                                    <table style="text-align: right;">
                                        <thead>
                                        <tr>
                                            <th style="font-weight: normal;">${l.t("from")}:</th>
                                            <th style="font-weight: normal;">${$(this.timeframe[0]).format("lll")}</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <tr>
                                            <td>${l.t("to")}:</td>
                                            <td>${$(this.timeframe[1]).format("lll")}</td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            `:void 0}
                            ${this.attributeControls?e`
                                <or-mwc-input class="button" .type="${A.BUTTON}" ?disabled="${t}" label="selectAttributes" icon="plus" @or-mwc-input-changed="${()=>this._openDialog()}"></or-mwc-input>
                            `:void 0}
                        </div>
                        ${R(this.showLegend?e`
                            <div id="attribute-list" class="${this.denseLegend?"attribute-list-dense":void 0}">
                                ${null==this.assetAttributes||0==this.assetAttributes.length?e`
                                    <div>
                                        <span>${l.t("noAttributesConnected")}</span>
                                    </div>
                                `:void 0}
                                ${this.assetAttributes&&this.assetAttributes.map(([t,i],r)=>{var o,a;let s=this.assets[t],n=r%this.colors.length,d=null==(o=this.attributeColors.find(t=>t[0].id===s.id&&t[0].name===i.name))?void 0:o[1],c=h.getAttributeAndValueDescriptors(s.type,i.name,i),p=v.getAttributeLabel(i,c[0],s.type,!0),m=(null==(a=this.attributeConfig.rightAxisAttributes)?void 0:a.find(t=>s.id===t.id&&i.name===t.name))?l.t("right"):void 0,u=(null!=d?d:this.colors[n])||"";return e`
                                        <div class="attribute-list-item ${this.denseLegend?"attribute-list-item-dense":void 0}"
                                             @mouseenter="${()=>this._addDatasetHighlight({id:this.assets[t].id,name:i.name})}"
                                             @mouseleave="${()=>this._removeDatasetHighlights()}">
                                            <span style="margin-right: 10px; --or-icon-width: 20px;">${P(h.getAssetDescriptor(this.assets[t].type),void 0,void 0,u.split("#")[1])}</span>
                                            <div class="attribute-list-item-label ${this.denseLegend?"attribute-list-item-label-dense":void 0}">
                                                <div style="display: flex; gap: 4px;">
                                                    <span style="font-size:12px; ${this.denseLegend?"margin-right: 8px":void 0}">${this.assets[t].name}</span>
                                                    ${z(m,()=>e`<span style="font-size:12px; color:grey">(${m})</span>`)}
                                                </div>
                                                <span style="font-size:12px; color:grey;">${p}</span>
                                            </div>
                                        </div>
                                    `})}
                            </div>
                        `:void 0)}
                    </div>
                `:void 0}
            </div>
        `}_onTreeSelectionChanged(t){return __awaiter(this,void 0,void 0,function*(){if(!c.events)return;let e=t.detail&&t.detail.newNodes.length>0?t.detail.newNodes[0]:void 0;if(e){let t=yield c.events.sendEventWithReply({eventType:"read-asset",assetId:e.asset.id});this.activeAsset=t.asset}else this.activeAsset=void 0})}_removeDatasetHighlights(t=this._chart){if(t){let e=t.getOption();e.series&&Array.isArray(e.series)&&e.series.forEach(function(t){.2===t.lineStyle.opacity||.99===t.lineStyle.opacity?(t.lineStyle.opacity=.31,t.showSymbol=!1):(t.lineStyle.opacity=1,t.showSymbol=!0)}),t.setOption(e)}}_addDatasetHighlight(t,e=this._chart){if(e){let i=e.getOption();i.series&&Array.isArray(i.series)&&i.series.forEach(e=>{e.assetId!==t.id||e.attrName!==t.name?.31===e.lineStyle.opacity?e.lineStyle.opacity=.2:(e.lineStyle.opacity=.3,e.showSymbol=!1):.31===e.lineStyle.opacity&&(e.lineStyle.opacity=.99,e.showSymbol=!0)}),e.setOption(i)}}loadSettings(t){return __awaiter(this,void 0,void 0,function*(){if((void 0===this.assetAttributes||t)&&(this.assetAttributes=[]),null!=this.realm||(this.realm=c.getRealm()),null!=this.timePrefixOptions||(this.timePrefixOptions=this._getDefaultTimePrefixOptions()),null!=this.timeWindowOptions||(this.timeWindowOptions=this._getDefaultTimeWindowOptions()),null!=this.timeWindowKey||(this.timeWindowKey=this.timeWindowOptions.keys().next().value.toString()),null!=this.timePrefixKey||(this.timePrefixKey=this.timePrefixOptions[1]),!this.panelName)return;let e=window.location.hash,i=(yield c.console.retrieveData("OrChartConfig"))||[];Array.isArray(i)||c.console.storeData("OrChartConfig",[i]);let r=i.find(t=>t.realm===this.realm);if(!r)return;let o=r.views&&r.views[e]?r.views[e][this.panelName]:void 0;if(!o)return;if(!o.attributeRefs){delete r.views[e][this.panelName];let t=[...i.filter(t=>t.realm!==this.realm),r];c.console.storeData("OrChartConfig",t);return}let a=o.attributeRefs.map(t=>t.id);if(0!==a.length&&(this._loading=!0,!a.every(t=>!!this.assets.find(e=>e.id===t)))){try{let t=(yield c.rest.api.AssetResource.queryAssets({ids:a})).data||[];o.attributeRefs=o.attributeRefs.filter(e=>!!t.find(t=>t.id===e.id&&t.attributes&&t.attributes.hasOwnProperty(e.name))),c.console.storeData("OrChartConfig",[...i.filter(t=>t.realm!==this.realm),r]),this.assets=t.filter(t=>o.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=o.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))}})}saveSettings(){return __awaiter(this,void 0,void 0,function*(){if(!this.panelName)return;let t=window.location.hash,e=(yield c.console.retrieveData("OrChartConfig"))||[],i=e.find(t=>t.realm===this.realm);null!=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)}):delete i.views[t][this.panelName],c.console.storeData("OrChartConfig",[...e.filter(t=>t.realm!==this.realm),i])})}_openDialog(){L(new T().setShowOnlyDatapointAttrs(!0).setMultiSelect(!0).setSelectedAttributes(this._getSelectedAttributes())).addEventListener(E.NAME,t=>this._addAttribute(t.detail))}_openTimeDialog(t,i){let r=N(),o=N();L(new k().setHeading(l.t("timeframe")).setContent(()=>e`
                <div>
                    <or-mwc-input ${H(r)} type="${A.DATETIME}" required label="${l.t("start")}" .value="${t}"></or-mwc-input>
                    <or-mwc-input ${H(o)} type="${A.DATETIME}" required label="${l.t("ending")}" .value="${i}"></or-mwc-input>
                </div>
            `).setActions([{actionName:"cancel",content:"cancel"},{actionName:"ok",content:"ok",action:()=>{var t,e;(null==(t=r.value)?void 0:t.value)&&(null==(e=o.value)?void 0:e.value)&&(this._isCustomWindow=!0,this.timeframe=[new Date(r.value.value),new Date(o.value.value)])}}]))}_addAttribute(t){return __awaiter(this,void 0,void 0,function*(){if(t){for(let e of(this.assetAttributes=[],t)){let t=yield c.rest.api.AssetResource.get(e.id);if(this.activeAsset=t.data,this.activeAsset){let t=this.assets.findIndex(t=>t.id===e.id);t<0&&(t=this.assets.length,this.assets=[...this.assets,this.activeAsset]),this.assetAttributes.push([t,e])}}this.assetAttributes=[...this.assetAttributes],this.saveSettings()}})}_getSelectedAttributes(){return this.assetAttributes.map(([t,e])=>({id:this.assets[t].id,name:e.name}))}_cleanup(){this._chart&&(this._toggleChartEventListeners(!1),this._chart.dispose(),this._chart=void 0,this.requestUpdate())}_getDefaultTimePrefixOptions(){return["this","last"]}_getDefaultTimeWindowOptions(){return new Map([["Hour",["hours",1]],["6Hours",["hours",6]],["24Hours",["hours",24]],["Day",["days",1]],["7Days",["days",7]],["Week",["weeks",1]],["30Days",["days",30]],["Month",["months",1]],["365Days",["days",365]],["Year",["years",1]]])}_getTimeSelectionDates(t,e){let i=$(),r=$(),o=this.timeWindowOptions.get(e);if(!o)throw Error(`Unsupported time window selected: ${e}`);let[a,s]=o;switch(t){case"this":1===s?(i=$().startOf(a),r=$().endOf(a)):(i=$().subtract(.5*s,a),r=$().add(.5*s,a));break;case"last":i=$().subtract(s,a).startOf(a),r=1===s?$().startOf(a):$()}return[i.toDate(),r.toDate()]}_shiftTimeframe(t,e,i,r){let o=this.timeWindowOptions.get(i);if(!o)throw Error(`Unsupported time window selected: ${i}`);let[a,s]=o,n=$(t);"previous"===r?n.subtract(s,a):n.add(s,a);let l=$(e);"previous"===r?l.subtract(s,a):l.add(s,a),this.timeframe=[n.toDate(),l.toDate()]}_getInterval(t){if(t<=1)return[5,"MINUTE"];if(t<=3)return[10,"MINUTE"];if(t<=6)return[30,"MINUTE"];if(t<=24)return[1,"HOUR"];if(t<=48)return[3,"HOUR"];else if(t<=96)return[12,"HOUR"];else if(t<=744)return[1,"DAY"];else return[1,"MONTH"]}_loadData(){return __awaiter(this,void 0,void 0,function*(){var t;let e;if(this._data&&!this._zoomChanged||!this.assetAttributes||!this.assets||0===this.assets.length&&!this.dataProvider||0===this.assetAttributes.length&&!this.dataProvider||!this.datapointQuery)return;if(this._loading)if(!this._dataAbortController)return;else this._dataAbortController.abort("Data request overridden"),delete this._dataAbortController;this._loading=!0,this._latestError=void 0;let i=this._getTimeSelectionDates(this.timePrefixKey,this.timeWindowKey),r=[];this._zoomChanged&&this._startOfPeriod&&this._endOfPeriod||(this._startOfPeriod=this.timeframe?this.timeframe[0].getTime():i[0].getTime(),this._endOfPeriod=this.timeframe?this.timeframe[1].getTime():i[1].getTime());try{this.dataProvider&&!this._zoomChanged?yield this.dataProvider(this._startOfPeriod,this._endOfPeriod).then(t=>{t.forEach(t=>r.push(t))}):(this._dataAbortController=new AbortController,e=this.assetAttributes.map((t,e)=>__awaiter(this,[t,e],void 0,function*([t,e],i){var o,a,s,n,d,c,p,m,u,f,g,y,b,_;let w=this.assets[t],x=!!(null==(a=null==(o=this.attributeConfig)?void 0:o.rightAxisAttributes)?void 0:a.find(t=>t.id===w.id&&t.name===e.name)),O=!!(null==(n=null==(s=this.attributeConfig)?void 0:s.smoothAttributes)?void 0:n.find(t=>t.id===w.id&&t.name===e.name)),C=this.stacked,A=!!(null==(c=null==(d=this.attributeConfig)?void 0:d.steppedAttributes)?void 0:c.find(t=>t.id===w.id&&t.name===e.name)),$=!!(null==(m=null==(p=this.attributeConfig)?void 0:p.areaAttributes)?void 0:m.find(t=>t.id===w.id&&t.name===e.name)),D=!!(null==(f=null==(u=this.attributeConfig)?void 0:u.faintAttributes)?void 0:f.find(t=>t.id===w.id&&t.name===e.name)),P=!!(null==(y=null==(g=this.attributeConfig)?void 0:g.extendedAttributes)?void 0:y.find(t=>t.id===w.id&&t.name===e.name)),S=null==(b=this.attributeColors.find(t=>t[0].id===w.id&&t[0].name===e.name))?void 0:b[1],T=h.getAttributeAndValueDescriptors(w.type,e.name,e),E=v.getAttributeLabel(e,T[0],w.type,!1),k=v.resolveUnits(v.getAttributeUnits(e,T[0],w.type)),L=i%this.colors.length,R={signal:null==(_=this._dataAbortController)?void 0:_.signal},W=yield this._loadAttributeData(w,e,null!=S?S:this.colors[L],!1,O,C,A,$,D,!1,`${w.name} | ${E}`,R,k);W.assetId=w.id,W.attrName=e.name,W.unit=k,W.yAxisIndex=+!!x,r.push(W),W=yield this._loadAttributeData(this.assets[t],e,null!=S?S:this.colors[L],!0,O,C,A,$,D,!1,`${w.name} | ${E} ${l.t("predicted")}`,R,k),r.push(W),P&&((W=yield this._loadAttributeData(this.assets[t],e,null!=S?S:this.colors[L],!1,!1,C,!1,$,D,P,`${w.name} | ${E} lastKnown`,R,k)).yAxisIndex=+!!x,r.push(W))}))),e&&(yield Promise.all(e)),this._data=r,this._loading=!1,this._zoomChanged=!1}catch(e){if(console.error(e),(null==e?void 0:e.message)==="canceled")return;if(this._loading=!1,this._zoomChanged=!1,S(e)){if(e.message.includes("timeout")){this._latestError="noAttributeDataTimeout";return}else if((null==(t=e.response)?void 0:t.status)===413){this._latestError="datapointRequestTooLarge";return}}this._latestError="errorOccurred"}})}_loadAttributeData(t,e,i,r,o,a,s,n,l,d,h,p,m){return __awaiter(this,void 0,void 0,function*(){var m,u,f,v;function y(t,e){return`rgba(${parseInt(t.slice(-6,-4),16)}, ${parseInt(t.slice(-4,-2),16)}, ${parseInt(t.slice(-2),16)}, ${e})`}let b={name:h,type:"line",data:[],sampling:"lttb",lineStyle:{color:i,type:r?[2,4]:d?[10,2]:void 0,opacity:l?.31:1},symbol:"circle",showSymbol:!l,itemStyle:{color:i},stack:a?d?"extended":"total":void 0,smooth:o,step:s?"end":void 0,extended:d,predicted:r,areaStyle:n?{color:new g.graphic.LinearGradient(0,0,0,1,[{offset:0,color:y(i,l?.1:.5)},{offset:1,color:y(i,0)}])}:void 0};if(t.id&&e.name&&this.datapointQuery){let i,o=JSON.parse(JSON.stringify(this.datapointQuery));if("lttb"===o.type)o.amountOfPoints?(null==(m=this._chartElem)?void 0:m.clientWidth)>0&&(o.amountOfPoints=Math.min(o.amountOfPoints,null==(u=this._chartElem)?void 0:u.clientWidth)):(null==(f=this._chartElem)?void 0:f.clientWidth)>0?o.amountOfPoints=Math.round(this._chartElem.clientWidth/10):(console.warn("Could not grab width of the Chart for estimating amount of data points. Using 100 points instead."),o.amountOfPoints=100);else if("interval"===o.type&&!o.interval){let t=(this.datapointQuery.toTimestamp-this.datapointQuery.fromTimestamp)/1e3/60/60,e=this._getInterval(t);o.interval=e[0].toString()+" "+e[1].toString()}this._zoomChanged?(o.fromTimestamp=this._zoomStartOfPeriod,o.toTimestamp=this._zoomEndOfPeriod):(o.fromTimestamp=this._startOfPeriod,o.toTimestamp=this._endOfPeriod),r?i=yield c.rest.api.AssetPredictedDatapointResource.getPredictedDatapoints(t.id,e.name,o,p):(d&&(o.type="nearest",o.timestamp=new Date().toISOString()),i=yield c.rest.api.AssetDatapointResource.getDatapoints(t.id,e.name,o,p));if(200===i.status&&(b.data=i.data.filter(t=>null!==t.y&&void 0!==t.y).map(t=>({x:t.x,y:t.y})).map(t=>[t.x,t.y])),d){let t=null==(v=b.data)?void 0:v[0];if(void 0!==t){let e=new Date(t[0]).getTime()<o.fromTimestamp?new Date(o.fromTimestamp).toISOString():t[0],i=new Date().getTime(),r=o.toTimestamp<i?new Date(o.toTimestamp).toISOString():new Date().toISOString();b.data=[[e,t[1]],[r,t[1]]]}}}return b})}_onZoomChange(t){var e,i;this._zoomChanged=!0;let{start:r,end:o}=null!=(i=null==(e=t.batch)?void 0:e[0])?i:t;this._zoomStartOfPeriod=this._startOfPeriod+(this._endOfPeriod-this._startOfPeriod)*r/100,this._zoomEndOfPeriod=this._startOfPeriod+(this._endOfPeriod-this._startOfPeriod)*o/100,this._loadData().then(()=>{this._updateChartData()})}_updateChartData(t=this._data,e=this._startOfPeriod,i=this._endOfPeriod){if(!this._chart)return void console.error("Could not update chart data; the chart is not initialized yet.");this._chart.setOption({xAxis:{min:e,max:i},series:null==t?void 0:t.map(t=>Object.assign(Object.assign({},t),{markLine:{symbol:"none",silent:!0,data:[{name:"",xAxis:new Date().toISOString(),label:{formatter:"{b}"}}],lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color"),type:"solid",width:1,opacity:1}}}))})}_toggleChartEventListeners(t){var e;t?(window.addEventListener("resize",()=>this._chart.resize()),this._containerResizeObserver=new ResizeObserver(()=>{this.applyChartResponsiveness(),this._chart.resize()}),this.shadowRoot&&this._containerResizeObserver.observe(this.shadowRoot.getElementById("container")),this._zoomHandler=this._chart.on("datazoom",W(t=>{this._onZoomChange(t)},750))):t||(this._chart.off("datazoom",this._zoomHandler),null==(e=this._containerResizeObserver)||e.disconnect(),this._containerResizeObserver=void 0)}_getTooltipData(t){var e;let i=[];return null==(e=this._data)||e.forEach(e=>{var r,o;let a=t>$().toDate().getTime();if(e.data&&e.data.length>0&&!e.extended&&e.predicted===a){let a=e.name,s=0,n=e.data.length-1,l=null,d=null,h=null,c=!1;for(;s<=n;){let i=Math.floor((s+n)/2),[r,o]=e.data[i];if(r===t){h=o,c=!0;break}r<t?(l={timestamp:r,value:o},s=i+1):(d={timestamp:r,value:o},n=i-1)}l&&l.timestamp>t&&(l=null),d&&d.timestamp<t&&(d=null),c||(l&&d&&!e.step?h=parseFloat((l.value+(t-l.timestamp)/(d.timestamp-l.timestamp)*(d.value-l.value)).toFixed(2)):!l&&d?h=d.value:l&&(!d||"end"==e.step)&&(h=l.value)),null!=h&&i.push({value:h,text:`<div><span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color: ${null==(r=e.lineStyle)?void 0:r.color}"></span> ${a}: <b>${h}${null!=(o=e.unit)?o:""}</b></div>`})}}),i.sort((t,e)=>e.value-t.value),i.map(t=>t.text).join("")}_getDefaultAttributeConfig(){return{rightAxisAttributes:[],smoothAttributes:[],steppedAttributes:[],areaAttributes:[],faintAttributes:[],extendedAttributes:[]}}};OrChart.DEFAULT_COLORS=["#3869B1","#DA7E30","#3F9852","#CC2428","#6B4C9A","#922427","#958C3D","#535055"],__decorate([a({type:Object})],OrChart.prototype,"assets",void 0),__decorate([a({type:Object})],OrChart.prototype,"activeAsset",void 0),__decorate([a({type:Object})],OrChart.prototype,"assetAttributes",void 0),__decorate([a({type:Array})],OrChart.prototype,"attributeColors",void 0),__decorate([a({type:Object})],OrChart.prototype,"attributeConfig",void 0),__decorate([a()],OrChart.prototype,"dataProvider",void 0),__decorate([a({type:Array})],OrChart.prototype,"colors",void 0),__decorate([a({type:Object})],OrChart.prototype,"datapointQuery",void 0),__decorate([a({type:Object})],OrChart.prototype,"config",void 0),__decorate([a({type:Object})],OrChart.prototype,"chartOptions",void 0),__decorate([a({type:String})],OrChart.prototype,"realm",void 0),__decorate([a()],OrChart.prototype,"panelName",void 0),__decorate([a({type:Boolean})],OrChart.prototype,"attributeControls",void 0),__decorate([a()],OrChart.prototype,"timeframe",void 0),__decorate([a({type:Boolean})],OrChart.prototype,"timestampControls",void 0),__decorate([a({type:Array})],OrChart.prototype,"timePrefixOptions",void 0),__decorate([a({type:String})],OrChart.prototype,"timePrefixKey",void 0),__decorate([a({type:Object})],OrChart.prototype,"timeWindowOptions",void 0),__decorate([a({type:String})],OrChart.prototype,"timeWindowKey",void 0),__decorate([a({type:Boolean})],OrChart.prototype,"stacked",void 0),__decorate([a({type:Boolean})],OrChart.prototype,"showLegend",void 0),__decorate([a({type:Boolean})],OrChart.prototype,"denseLegend",void 0),__decorate([a({type:Boolean})],OrChart.prototype,"showZoomBar",void 0),__decorate([s()],OrChart.prototype,"_loading",void 0),__decorate([s()],OrChart.prototype,"_data",void 0),__decorate([a()],OrChart.prototype,"_tableTemplate",void 0),__decorate([s()],OrChart.prototype,"_zoomChanged",void 0),__decorate([s()],OrChart.prototype,"_isCustomWindow",void 0),__decorate([n("#chart")],OrChart.prototype,"_chartElem",void 0),OrChart=OrChart_1=__decorate([o("or-chart")],OrChart);export{OrChart};