var OrAttributeBarChart_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{i18next as l}from"@openremote/or-translate";import{AssetModelUtil as d}from"@openremote/model";import m,{DefaultColor3 as h,DefaultColor4 as u,Util as c}from"@openremote/core";import*as p from"echarts/core";import{DataZoomComponent as f,GridComponent as v,TooltipComponent as y}from"echarts/components";import{BarChart as g}from"echarts/charts";import{CanvasRenderer as _}from"echarts/renderers";import{UniversalTransition as b}from"echarts/features";import{InputType as O}from"@openremote/or-mwc-components/or-mwc-input";import x from"moment";import{getAssetDescriptorIconTemplate as w}from"@openremote/or-icon";import{isAxiosError as C}from"@openremote/rest";import{OrMwcDialog as A,showDialog as E}from"@openremote/or-mwc-components/or-mwc-dialog";import{showSnackbar as $}from"@openremote/or-mwc-components/or-mwc-snackbar";import{cache as N}from"lit/directives/cache.js";import"@openremote/or-mwc-components/or-mwc-menu";import{getContentWithMenuTemplate as T}from"@openremote/or-mwc-components/or-mwc-menu";import{when as M}from"lit/directives/when.js";import{createRef as D,ref as B}from"lit/directives/ref.js";import"@openremote/or-translate";p.use([v,y,f,g,_,b]);export var BarChartInterval;!function(t){t.AUTO="auto",t.NONE="none",t.ONE_MINUTE="1Minute",t.FIVE_MINUTES="5Minutes",t.THIRTY_MINUTES="30Minutes",t.ONE_HOUR="hour",t.ONE_DAY="day",t.ONE_WEEK="week",t.ONE_MONTH="month",t.ONE_YEAR="year"}(BarChartInterval||(BarChartInterval={}));let style=t`
    :host {
        --internal-or-chart-text-color: var(--or-chart-text-color, var(--or-app-color3, ${r(h)}));
        --internal-or-chart-graph-fill-color: var(--or-chart-graph-fill-color, var(--or-app-color4, ${r(u)}));
        --internal-or-chart-graph-point-hover-border-color: var(--or-chart-graph-point-hover-border-color, var(--or-app-color3, ${r(h)}));
        width: 100%;
        display: block;
    }

    .button-icon {
        align-self: center;
        padding: 10px;
        cursor: pointer;
    }

    .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%;
    }

    #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;
    }

    .navigate {
        flex-direction: column;
    }

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

    #attribute-list {
        overflow: hidden auto;
        min-height: 50px;
        flex: 1 1 0;
        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;
    }

    .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;
    }

    #controls > * {
        margin-top: 5px;
        margin-bottom: 5px;
    }

    .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;
        /*min-height: 400px;
        max-height: 550px;*/
    }

    #chart-controls {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        margin-right: -4px;
    }

    #chart {
        width: 100%;
        height: 100%;
    }

    @media screen and (max-width: 1280px) {
        #chart-container {
        }
    }

    @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;
        }

        .interval-controls,
        #period-controls {
            flex-direction: row;
            justify-content: left;
            align-items: center;
            gap: 8px;
        }
    }
`,OrAttributeBarChart=OrAttributeBarChart_1=class extends i{constructor(){super(...arguments),this.assets=[],this.assetAttributes=[],this.realm=null==m?void 0:m.displayRealm,this.attributeColors=[],this.colors=OrAttributeBarChart_1.DEFAULT_COLORS,this.showLegend=!1,this.denseLegend=!1,this.stacked=!1,this.timestampControls=!0,this.decimals=2,this.timePrefixOptions=OrAttributeBarChart_1.getDefaultTimePrefixOptions(),this.timeWindowOptions=OrAttributeBarChart_1.getDefaultTimeWindowOptions(),this.intervalOptions=OrAttributeBarChart_1.getDefaultIntervalOptions(),this._isCustomWindow=!1,this._loading=!1}static get styles(){return[style]}connectedCallback(){super.connectedCallback(),this._style=window.getComputedStyle(this)}disconnectedCallback(){super.disconnectedCallback(),this._cleanup()}willUpdate(t){return t.has("realm")&&t.get("realm")&&(this.assets=[],this.assetAttributes=[]),t.has("timePrefixOptions")&&this.timePrefixOptions&&(null!=this.timePrefixKey||(this.timePrefixKey=this.timePrefixOptions[0])),t.has("timeWindowOptions")&&this.timeWindowOptions&&(null!=this.timeWindowKey||(this.timeWindowKey=Array.from(this.timeWindowOptions.keys())[0])),t.has("intervalOptions")&&this.intervalOptions&&(null!=this.interval||(this.interval=Array.from(this.intervalOptions.keys())[0])),super.willUpdate(t)}updated(t){var e,i,r;if(super.updated(t),t.has("attributeColors")||t.has("datapointQuery")||t.has("timeframe")||t.has("interval")||t.has("timePrefixKey")||t.has("timeWindowKey")||t.has("attributeConfig")||t.has("assetAttributes")||t.has("realm")){this._data=void 0,this._chart&&this._cleanup();let t=this._getTimeSelectionDates(this.timePrefixKey,this.timeWindowKey);this._startOfPeriod=this.timeframe?this.timeframe[0].getTime():t[0].getTime(),this._endOfPeriod=this.timeframe?this.timeframe[1].getTime():t[1].getTime(),this._intervalConfig=this._getInterval(this._startOfPeriod,this._endOfPeriod,this.interval),this._loadData()}this._data&&(this._chart||(console.debug("Initializing chart..."),this.chartOptions=Object.assign(Object.assign({},this._getDefaultChartOptions()),this.chartOptions),this._chart=p.init(this._chartElem),this._chart.setOption(this.chartOptions),this._toggleChartEventListeners(!0)),t.has("_data")&&(null==(r=null==(i=null==(e=this._data)?void 0:e[0])?void 0:i.data)?void 0:r.length)&&this._updateChartData())}render(){var t;let i=this._loading||!!this._latestError;return e`
            <div id="container">
                ${M(this._loading,()=>e`
                    <div style="position: absolute; height: 100%; width: 100%;">
                        <or-loading-indicator ?overlay="false"></or-loading-indicator>
                    </div>
                `)}
                ${M(this._latestError,()=>{var t;return e`
                    <div style="position: absolute; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;">
                        <or-translate .value="${null!=(t=this._latestError)?t:"errorOccurred"}"></or-translate>
                    </div>
                `})}
                ${M(Object.keys(this.attributeConfig||{}).filter(t=>t.startsWith("method")).every(t=>0===this.attributeConfig[t].length),()=>e`
                    <div style="position: inherit; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; z-index: 1; pointer-events: none;">
                        <or-translate .value="${"dashboard.selectMethod"}"></or-translate>
                    </div>
                `)}
                ${M(null==(t=this._data)?void 0:t.every(t=>{var e;return!(null==(e=t.data)?void 0:e.length)}),()=>e`
                    <div style="position: inherit; height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; z-index: 1; pointer-events: none;">
                        <or-translate .value="${"dashboard.noData"}"></or-translate>
                    </div>
                `)}
                <div id="chart-container">
                    <div id="chart" style="visibility: ${i?"hidden":"visible"}"></div>
                </div>

                ${M(this.timestampControls||this.showLegend,()=>e`
                    <div id="chart-controls">
                        <div id="controls">
                            ${M(this.timestampControls&&this.timePrefixKey&&this.timePrefixOptions&&this.timeWindowKey&&this.timeWindowOptions,()=>this._getTimeControlsTemplate(i||!!this.timeframe),()=>{var t,i,r,o;return e`
                                        <div style="display: flex; justify-content: center;">
                                            <or-mwc-input .type="${O.BUTTON}" label="${l.t(null!=(i=null==(t=this.timePrefixKey)?void 0:t.toLowerCase())?i:"???")}" disabled style="margin-right: -2px;"></or-mwc-input>
                                            <or-mwc-input .type="${O.BUTTON}" label="${l.t(null!=(o=null==(r=this.timeWindowKey)?void 0:r.toLowerCase())?o:"???")}" disabled style="margin-left: -2px;"></or-mwc-input>
                                        </div>
                                    `})}
                            ${M(this.timeframe,()=>this._getTimeframeStatusTemplate(this.timeframe))}
                        </div>
                        ${N(M(this.showLegend,()=>this._getLegendTemplate()))}
                    </div>
                `)}
            </div>
        `}_getTimeControlsTemplate(t=!0){var i,r,o,a;return e`
            <div id="period-controls">
                <div id="period-dropdown-controls">
                    <!-- Time prefix selection -->
                    ${T(e`<or-mwc-input .type="${O.BUTTON}" label="${this.timeframe?"dashboard.customTimeSpan":this.timePrefixKey}" ?disabled="${t}"></or-mwc-input>`,t?null:this.timePrefixOptions.map(t=>({value:t})),this.timePrefixKey,t=>{this.timeframe=void 0,this.timePrefixKey=t.toString()},void 0,void 0,void 0,!0)}
                    <!-- Time window selection -->
                    ${T(e`<or-mwc-input .type="${O.BUTTON}" label="${this._isCustomWindow?"timeframe":l.t(null!=(r=null==(i=this.timeWindowKey)?void 0:i.toLowerCase())?r:"")}" ?disabled="${t}"></or-mwc-input>`,t?null:Array.from(this.timeWindowOptions.keys()).map(t=>({value:t,text:t.toLowerCase(),translate:!0})),this.timeWindowKey,t=>{this.timeframe=void 0,this.timeWindowKey=t.toString()},void 0,void 0,void 0,!0)}
                </div>
                <!-- Interval selection -->
                ${T(e`<or-mwc-input .type="${O.BUTTON}" label="${l.t(`intervalBy${null==(a=null==(o=this._intervalConfig)?void 0:o.displayName)?void 0:a.toLowerCase()}`)}"></or-mwc-input>`,Array.from(this.intervalOptions.keys()).map(t=>({value:t,text:`intervalBy${t.toLowerCase()}`,translate:!0})),this.interval,t=>this.interval=t,void 0,void 0,void 0,!0)}
            </div>
            <div class="navigate" style="text-align: right">
                <!-- Scroll left button -->
                <or-icon class="button button-icon" ?disabled="${t}" icon="chevron-left"
                         @click="${()=>this._shiftTimeframe(this.timeframe?this.timeframe[0]:new Date(this._startOfPeriod),this.timeframe?this.timeframe[1]:new Date(this._endOfPeriod),this.timeWindowKey,"previous")}"></or-icon>
                <!-- Scroll right button -->
                <or-icon class="button button-icon" ?disabled="${t}" icon="chevron-right"
                         @click="${()=>this._shiftTimeframe(this.timeframe?this.timeframe[0]:new Date(this._startOfPeriod),this.timeframe?this.timeframe[1]: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>
        `}_getTimeframeStatusTemplate(t=this.timeframe){return e`
            <div style="margin-left: 18px; font-size: 12px; display: flex; justify-content: flex-end;">
                <table style="text-align: right;">
                    <thead>
                    <tr>
                        <th style="font-weight: normal; text-align: right;"><or-translate value="from"></or-translate></th>
                        <th style="font-weight: normal; text-align: right;">${x(t[0]).format("lll")}</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td style="text-align: right;"><or-translate value="to"></or-translate></td>
                        <td style="text-align: right;">${x(t[1]).format("lll")}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        `}_getLegendTemplate(){return e`
            <div id="attribute-list" class="${this.denseLegend?"attribute-list-dense":void 0}">
                ${M(null==this.assetAttributes||0===this.assetAttributes.length,()=>e`
                    <div>
                        <or-translate value="noAttributesConnected"></or-translate>
                    </div>
                `)}
                ${this.assetAttributes&&this.assetAttributes.map(([t,i],r)=>{var o,a,s;let n=this.assets[t];if(!n)return e`Error`;let m=r%this.colors.length,h=null==(o=this.attributeColors.find(t=>t[0].id===n.id&&t[0].name===i.name))?void 0:o[1],u=d.getAttributeAndValueDescriptors(n.type,i.name,i),p=c.getAttributeLabel(i,u[0],n.type,!0),f=(null==(s=null==(a=this.attributeConfig)?void 0:a.rightAxisAttributes)?void 0:s.find(t=>n.id===t.id&&i.name===t.name))?l.t("right"):void 0,v=(null!=h?h:this.colors[m])||"",y=Object.entries(this.attributeConfig||{}).filter(([t])=>t.includes("method")).sort(([t],[e])=>t.localeCompare(e)).reduce((t,[e,r])=>(r.some(t=>t.id===n.id&&t.name===i.name)&&t.push(l.t(`${e}-short`)),t),[]);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;">${w(d.getAssetDescriptor(this.assets[t].type),void 0,void 0,v.split("#")[1])}</span>
                            <div class="attribute-list-item-label ${this.denseLegend?"attribute-list-item-label-dense":void 0}">
                                <div style="display: flex; justify-content: space-between;">
                                    <span style="font-size:12px; ${this.denseLegend?"margin-right: 8px":void 0}">${this.assets[t].name}</span>
                                    ${M(f,()=>e`<span style="font-size:12px; color:grey">(${f})</span>`)}
                                </div>
                                <span style="font-size:12px; color:grey; white-space:pre-line;">${p} <br> (${y.join(", ")})</span>
                            </div>
                        </div>
                    `})}
            </div>
        `}_openTimeDialog(t,i){let r=D(),o=D();E(new A().setHeading(l.t("timeframe")).setContent(()=>e`
                <div>
                    <or-mwc-input ${B(r)} type="${O.DATETIME}" required label="${l.t("start")}" .value="${t}"></or-mwc-input>
                    <or-mwc-input ${B(o)} type="${O.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)&&r.value.value<o.value.value?(this._isCustomWindow=!0,this.timeframe=[new Date(r.value.value),new Date(o.value.value)]):$(void 0,l.t("errorOccurred"))}}]))}_removeDatasetHighlights(t=this._chart){var e;if(t){let i=t.getOption();null==(e=i.series)||e.forEach(t=>{null!=t.itemStyle||(t.itemStyle={}),.2===t.itemStyle.opacity||.99===t.itemStyle.opacity?t.itemStyle.opacity=.31:t.itemStyle.opacity=1}),t.setOption(i)}}_addDatasetHighlight(t,e=this._chart){var i;if(e){let r=e.getOption();null==(i=r.series)||i.forEach(e=>{null!=e.itemStyle||(e.itemStyle={}),e.assetId!==t.id||e.attrName!==t.name?.31===e.itemStyle.opacity?e.itemStyle.opacity=.2:e.itemStyle.opacity=.3:.31===e.itemStyle.opacity&&(e.itemStyle.opacity=.99)}),e.setOption(r)}}_applyChartResponsiveness(){var t,e,i;if(this.shadowRoot){let e=this.shadowRoot.getElementById("container");if(e){let i=e.clientWidth<600;e.style.flexDirection=i?"column":"row";let r=this.shadowRoot.getElementById("controls");r&&(r.style.flexDirection=i?"row":"column");let o=this.shadowRoot.getElementById("period-controls");o&&(o.style.flexDirection=i?"row":"column");let a=this.shadowRoot.getElementById("attribute-list");a&&(a.style.gap=i?"4px 12px":"",a.style.maxHeight=i?"90px":"",a.style.flexFlow=i?"row wrap":"column nowrap",a.style.padding=i?"0":"5px 0"),this.shadowRoot.querySelectorAll(".attribute-list-item").forEach(t=>{t.style.minHeight=i?"0px":"44px",t.style.paddingLeft=i?"":"16px",t.children[1].style.flexDirection=i?"row":"column",t.children[1].style.gap=i?"4px":""}),null==(t=this._chart)||t.resize()}}let r=Math.max(1,(this._endOfPeriod-this._startOfPeriod)/this._intervalConfig.millis-1),o=(null==(e=this._chartElem)?void 0:e.clientWidth)?this._chartElem.clientWidth/50:Number.MAX_SAFE_INTEGER,a=Math.max(1,Math.min(r,Math.floor(1.5*o)));null==(i=this._chart)||i.setOption({xAxis:{show:a>1,splitNumber:a,minInterval:this._intervalConfig.millis,axisLabel:{rotate:45*(a>o)}}})}_cleanup(){this._chart&&(console.debug("Destroying bar chart..."),this._toggleChartEventListeners(!1),this._chart.dispose(),this._chart=void 0,this.requestUpdate())}_getTimeSelectionDates(t,e){var i;let r=x(),o=x(),a=null==(i=this.timeWindowOptions)?void 0:i.get(e);if(!a)throw Error(`Unsupported time window selected: ${e}`);let[s,n]=a;switch(t){case"this":1===n?(r=x().startOf(s),o=x().endOf(s)):(r=x().subtract(.5*n,s),o=x().add(.5*n,s));break;case"last":r=x().subtract(n,s).startOf(s),o=1===n?x().startOf(s):x();break;default:console.error("Could not get time selection dates. The time prefix was not set correctly.")}return[r.toDate(),o.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=x(t);"previous"===r?n.subtract(s,a):n.add(s,a);let l=x(e);"previous"===r?l.subtract(s,a):l.add(s,a),this.timeframe=[n.toDate(),l.toDate()]}_getInterval(t,e,i,r=!1){let o=(e-t)/1e3/60/60,a=r?o:Math.round(o);if(i===BarChartInterval.AUTO)if(a<=1)return{displayName:"5Minutes-auto",steps:5,orFormat:"MINUTE",momentFormat:"minutes",millis:3e5};else if(a<=6)return{displayName:"30Minutes-auto",steps:30,orFormat:"MINUTE",momentFormat:"minutes",millis:18e5};else if(a<=24)return{displayName:"hour-auto",steps:1,orFormat:"HOUR",momentFormat:"hours",millis:36e5};else if(a<=744)return{displayName:"day-auto",steps:1,orFormat:"DAY",momentFormat:"days",millis:864e5};else if(a<=8760)return{displayName:"week-auto",steps:1,orFormat:"WEEK",momentFormat:"weeks",millis:6048e5};else return{displayName:"month-auto",steps:1,orFormat:"MONTH",momentFormat:"months",millis:2592e6};if(i===BarChartInterval.NONE){let t=this._endOfPeriod-this._startOfPeriod;return{displayName:"none",steps:Math.ceil(t/6e4),orFormat:"MINUTE",momentFormat:"minutes",millis:t}}let s=this.intervalOptions.get(i);if(x.duration(s.steps,s.momentFormat).asHours()<=a)return s;console.warn("Selected interval is larger than the timeframe! Changing to a valid timeframe...");let n=Array.from(this.intervalOptions.entries());for(let t=n.length-1;t>=0;t--){let[e,i]=n[t];if(x.duration(i.steps,i.momentFormat).asHours()<=a)return i}return n[0][1]}_loadData(){return __awaiter(this,void 0,void 0,function*(){var t;let e;if(this._data||!this.assetAttributes||!this.assets||0===this.assets.length||0===this.assetAttributes.length||!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=[];try{this._dataAbortController=new AbortController,(e=this.assetAttributes.map((t,e)=>__awaiter(this,[t,e],void 0,function*([t,e],r){var o,a,s,n,m,h,u,p,f,v,y,g,_,b,O,x,w,C,A,E,$,N;let T=this.assets[t],M=!!(null==(a=null==(o=this.attributeConfig)?void 0:o.rightAxisAttributes)?void 0:a.find(t=>t.id===T.id&&t.name===e.name)),D=null==(s=this.attributeColors.find(t=>t[0].id===T.id&&t[0].name===e.name))?void 0:s[1],B=d.getAttributeAndValueDescriptors(T.type,e.name,e),I=!!(null==(m=null==(n=this.attributeConfig)?void 0:n.faintAttributes)?void 0:m.find(t=>t.id===T.id&&t.name===e.name)),P=c.getAttributeLabel(e,B[0],T.type,!1),S=c.resolveUnits(c.getAttributeUnits(e,B[0],T.type)),F=r%this.colors.length,L={signal:null==(h=this._dataAbortController)?void 0:h.signal},W={AVG:{active:!!(null==(p=null==(u=this.attributeConfig)?void 0:u.methodAvgAttributes)?void 0:p.find(t=>t.id===T.id&&t.name===e.name)),formula:"AVG"},COUNT:{active:!!(null==(v=null==(f=this.attributeConfig)?void 0:f.methodCountAttributes)?void 0:v.find(t=>t.id===T.id&&t.name===e.name)),formula:"COUNT"},DIFFERENCE:{active:!!(null==(g=null==(y=this.attributeConfig)?void 0:y.methodDifferenceAttributes)?void 0:g.find(t=>t.id===T.id&&t.name===e.name)),formula:"DIFFERENCE"},MAX:{active:!!(null==(b=null==(_=this.attributeConfig)?void 0:_.methodMaxAttributes)?void 0:b.find(t=>t.id===T.id&&t.name===e.name)),formula:"MAX"},MEDIAN:{active:!!(null==(x=null==(O=this.attributeConfig)?void 0:O.methodMedianAttributes)?void 0:x.find(t=>t.id===T.id&&t.name===e.name)),formula:"MEDIAN"},MIN:{active:!!(null==(C=null==(w=this.attributeConfig)?void 0:w.methodMinAttributes)?void 0:C.find(t=>t.id===T.id&&t.name===e.name)),formula:"MIN"},MODE:{active:!!(null==(E=null==(A=this.attributeConfig)?void 0:A.methodModeAttributes)?void 0:E.find(t=>t.id===T.id&&t.name===e.name)),formula:"MODE"},SUM:{active:!!(null==(N=null==($=this.attributeConfig)?void 0:$.methodSumAttributes)?void 0:N.find(t=>t.id===T.id&&t.name===e.name)),formula:"SUM"}};for(let[t,o]of Object.entries(W).sort(([t],[e])=>t.localeCompare(e)))if(o.active){let a=yield this._loadAttributeData(T,e,null!=D?D:this.colors[F],this._startOfPeriod,this._endOfPeriod,o.formula,I,`${T.name} | ${P} 
${l.t(o.formula)}`,L,S);a.index=1e3*Object.keys(W).indexOf(t)+(r+1),a.assetId=T.id,a.attrName=e.name,a.unit=S,a.yAxisIndex=+!!M,a.color=null!=D?D:this.colors[F],i.push(a)}})))&&(yield Promise.all(e));let t=i.sort((t,e)=>e.index-t.index).reverse();if(this.stacked){let e=new Set(t.map(t=>t.stack));e.size>1&&e.forEach(e=>{let i=[...t].reverse().find(t=>t.stack===e);i&&(i.label.show=!0)})}this._data=t,this._loading=!1}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._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){return __awaiter(this,arguments,void 0,function*(t,e,i,r,o,a,s=!1,n,l,d){var h,u,c,p;let f=this._getDefaultDatasetOptions(null!=n?n:"",a,i,s);if(t.id&&e.name&&this.datapointQuery){let i=structuredClone(this.datapointQuery);i.fromTimestamp=r,i.toTimestamp=o-1,i.formula=a,i.gapFill=!0,i.interval=`${null!=(u=null==(h=this._intervalConfig)?void 0:h.steps)?u:"???"} ${null!=(p=null==(c=this._intervalConfig)?void 0:c.orFormat)?p:"???"}`,console.debug(`Requesting datapoints for '${e.name}' of ${t.id}, between ${x(r).format("lll")} and ${x(o-1).format("lll")}...`);let s=yield m.rest.api.AssetDatapointResource.getDatapoints(t.id,e.name,i,l);200===s.status&&(f.data=s.data.map(t=>({x:t.x,y:t.y})).map(t=>{var e,i;return[(null!=(e=t.x)?e:0)+.5*this._intervalConfig.millis,null==(i=t.y)?void 0:i.toFixed(this.decimals)]}))}return f})}_updateChartData(){var t,e,i,r,o,a,s;if(!this._chart)return void console.error("Could not update bar chart data; the bar chart is not initialized yet.");let n=null==(e=null==(t=this._data)?void 0:t[0])?void 0:e.data;if(n){let t=n[0][0];t!==this._startOfPeriod&&(this._startOfPeriod=t);let e=[...n].reverse()[0][0];e!==this._endOfPeriod&&(this._endOfPeriod=e)}let l=Math.max(1,(this._endOfPeriod-this._startOfPeriod)/this._intervalConfig.millis-1),d=(null==(i=this._chartElem)?void 0:i.clientWidth)?this._chartElem.clientWidth/50:Number.MAX_SAFE_INTEGER,m=Math.max(1,Math.min(l,Math.floor(1.5*d)));this._chart.setOption({xAxis:{show:m>1,splitNumber:m,minInterval:this._intervalConfig.millis,min:this._startOfPeriod,max:this._endOfPeriod,axisLabel:{interval:null==(r=this._intervalConfig)?void 0:r.millis,rotate:45*(m>d)}},dataZoom:{minValueSpan:(null!=(a=null==(o=this._intervalConfig)?void 0:o.millis)?a:0)*4},series:[...(null!=(s=this._data)?s:[]).map(t=>Object.assign({},t))]})}_toggleChartEventListeners(t){var e;t?(this._containerResizeObserver=new ResizeObserver(()=>this._applyChartResponsiveness()),this._containerResizeObserver.observe(this.shadowRoot.getElementById("container"))):(null==(e=this._containerResizeObserver)||e.disconnect(),this._containerResizeObserver=void 0)}_getDefaultChartOptions(){var t,e,i,r,o,a,s,n,d,m,h,u,c,p,f,v,y,g,_,b,O,w,C;let A=Math.max(1,(this._endOfPeriod-this._startOfPeriod)/this._intervalConfig.millis-1),E=(null==(t=this._chartElem)?void 0:t.clientWidth)?this._chartElem.clientWidth/50:Number.MAX_SAFE_INTEGER,$=Math.max(1,Math.min(A,Math.floor(1.5*E)));return{grid:{show:!0,backgroundColor:this._style.getPropertyValue("--internal-or-asset-tree-background-color"),borderColor:this._style.getPropertyValue("--internal-or-chart-text-color"),left:10,right:10,top:10,bottom:10,containLabel:!0},backgroundColor:this._style.getPropertyValue("--internal-or-asset-tree-background-color"),tooltip:{trigger:"axis",confine:!0,axisPointer:{type:"cross",label:{show:!0,formatter:t=>{var e,i,r,o,a;if("x"!==t.axisDimension)return Number(t.value).toFixed(this.decimals).toString();{let s=x(t.value),n=s.clone().subtract((null!=(i=null==(e=this._intervalConfig)?void 0:e.millis)?i:0)/2,"milliseconds"),d=s.clone().add((null!=(o=null==(r=this._intervalConfig)?void 0:r.millis)?o:0)/2,"milliseconds");switch(null==(a=this._intervalConfig)?void 0:a.orFormat){case"MINUTE":case"HOUR":return`${n.format("lll")} - ${d.format("lll")}`;case"DAY":return`${s.format("dddd, LL")}`;case"WEEK":return`${l.t("week")} ${n.format("w, LL")} - ${d.format("LL")}`;default:return`${n.format("LL")} - ${d.format("LL")}`}}}}}},xAxis:{type:"time",show:A>1,axisLine:{lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color")}},splitNumber:$,minInterval:this._intervalConfig.millis,min:this._startOfPeriod,max:this._endOfPeriod,boundaryGap:!1,splitArea:{show:!0,areaStyle:{color:["transparent","rgba(0, 0, 0, 0.05)"]}},axisLabel:{rotate:45*($>E),interval:null==(e=this._intervalConfig)?void 0:e.millis,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==(a=null==(o=null==(r=null==(i=this.chartOptions)?void 0:i.options)?void 0:r.scales)?void 0:o.y)?void 0:a.min,max:null==(m=null==(d=null==(n=null==(s=this.chartOptions)?void 0:s.options)?void 0:n.scales)?void 0:d.y)?void 0:m.max},{type:"value",show:(null!=(c=null==(u=null==(h=this.attributeConfig)?void 0:h.rightAxisAttributes)?void 0:u.length)?c:0)>0,axisLine:{lineStyle:{color:this._style.getPropertyValue("--internal-or-chart-text-color")}},boundaryGap:["10%","10%"],scale:!0,min:null==(y=null==(v=null==(f=null==(p=this.chartOptions)?void 0:p.options)?void 0:f.scales)?void 0:v.y1)?void 0:y.min,max:null==(O=null==(b=null==(_=null==(g=this.chartOptions)?void 0:g.options)?void 0:_.scales)?void 0:b.y1)?void 0:O.max}],dataZoom:[{type:"inside",minValueSpan:(null!=(C=null==(w=this._intervalConfig)?void 0:w.millis)?C:0)*4}],series:[]}}_getDefaultDatasetOptions(t,e,i,r=!1){let o=Object.entries(this.attributeConfig||{}).filter(([t,e])=>t.startsWith("method")&&(null==e?void 0:e.length)>0).length>1;return{name:t,type:"bar",data:[],stack:this.stacked?`${e}`:void 0,itemStyle:{color:i,opacity:r?.31:1},emphasis:{},label:{show:!this.stacked,align:"left",verticalAlign:"middle",position:"top",fontStyle:"italic",fontSize:10,rotate:90,distance:10,formatter:t=>{var i,r,a;if(o){let o=null==(a=null==(i=this._data)?void 0:i[null!=(r=t.seriesIndex)?r:0])?void 0:a.data;if((null==o?void 0:o.findIndex(t=>null!=t[1]))===t.dataIndex)return e}return""}}}}static getDefaultTimePrefixOptions(){return["this","last"]}static 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]]])}static getDefaultIntervalOptions(){return new Map([[BarChartInterval.AUTO,{displayName:"auto",steps:1,orFormat:"MINUTE",momentFormat:"minutes",millis:6e4}],[BarChartInterval.ONE_MINUTE,{displayName:"1Minute",steps:1,orFormat:"MINUTE",momentFormat:"minutes",millis:6e4}],[BarChartInterval.FIVE_MINUTES,{displayName:"5Minutes",steps:5,orFormat:"MINUTE",momentFormat:"minutes",millis:3e5}],[BarChartInterval.THIRTY_MINUTES,{displayName:"30Minutes",steps:30,orFormat:"MINUTE",momentFormat:"minutes",millis:18e5}],[BarChartInterval.ONE_HOUR,{displayName:"hour",steps:1,orFormat:"HOUR",momentFormat:"hours",millis:36e5}],[BarChartInterval.ONE_DAY,{displayName:"day",steps:1,orFormat:"DAY",momentFormat:"days",millis:864e5}],[BarChartInterval.ONE_WEEK,{displayName:"week",steps:1,orFormat:"WEEK",momentFormat:"weeks",millis:6048e5}],[BarChartInterval.ONE_MONTH,{displayName:"month",steps:1,orFormat:"MONTH",momentFormat:"months",millis:2592e6}],[BarChartInterval.ONE_YEAR,{displayName:"year",steps:1,orFormat:"YEAR",momentFormat:"years",millis:31536e6}]])}};OrAttributeBarChart.DEFAULT_COLORS=["#3869B1","#DA7E30","#3F9852","#CC2428","#6B4C9A","#922427","#958C3D","#535055"],__decorate([a({type:Object})],OrAttributeBarChart.prototype,"assets",void 0),__decorate([a({type:Object})],OrAttributeBarChart.prototype,"assetAttributes",void 0),__decorate([a({type:String})],OrAttributeBarChart.prototype,"realm",void 0),__decorate([a({type:Array})],OrAttributeBarChart.prototype,"attributeColors",void 0),__decorate([a({type:Object})],OrAttributeBarChart.prototype,"attributeConfig",void 0),__decorate([a({type:Array})],OrAttributeBarChart.prototype,"colors",void 0),__decorate([a({type:Object})],OrAttributeBarChart.prototype,"datapointQuery",void 0),__decorate([a({type:Array})],OrAttributeBarChart.prototype,"timeframe",void 0),__decorate([a({type:Object})],OrAttributeBarChart.prototype,"chartOptions",void 0),__decorate([a({type:Boolean})],OrAttributeBarChart.prototype,"showLegend",void 0),__decorate([a({type:Boolean})],OrAttributeBarChart.prototype,"denseLegend",void 0),__decorate([a({type:Boolean})],OrAttributeBarChart.prototype,"stacked",void 0),__decorate([a({type:Boolean})],OrAttributeBarChart.prototype,"timestampControls",void 0),__decorate([a({type:Number})],OrAttributeBarChart.prototype,"decimals",void 0),__decorate([a({type:Array})],OrAttributeBarChart.prototype,"timePrefixOptions",void 0),__decorate([a({type:String})],OrAttributeBarChart.prototype,"timePrefixKey",void 0),__decorate([a({type:Object})],OrAttributeBarChart.prototype,"timeWindowOptions",void 0),__decorate([a({type:String})],OrAttributeBarChart.prototype,"timeWindowKey",void 0),__decorate([a({type:Object})],OrAttributeBarChart.prototype,"intervalOptions",void 0),__decorate([a({type:String})],OrAttributeBarChart.prototype,"interval",void 0),__decorate([s()],OrAttributeBarChart.prototype,"_isCustomWindow",void 0),__decorate([s()],OrAttributeBarChart.prototype,"_loading",void 0),__decorate([s()],OrAttributeBarChart.prototype,"_data",void 0),__decorate([n("#chart")],OrAttributeBarChart.prototype,"_chartElem",void 0),OrAttributeBarChart=OrAttributeBarChart_1=__decorate([o("or-attribute-barchart")],OrAttributeBarChart);export{OrAttributeBarChart};