var OrAttributeHistory_1,__decorate=this&&this.__decorate||function(t,e,r,i){var o,a=arguments.length,s=a<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,r,i);else for(var n=t.length-1;n>=0;n--)(o=t[n])&&(s=(a<3?o(s):a>3?o(e,r,s):o(e,r))||s);return a>3&&s&&Object.defineProperty(e,r,s),s},__awaiter=this&&this.__awaiter||function(t,e,r,i){return new(r||(r=Promise))(function(o,a){function s(t){try{l(i.next(t))}catch(t){a(t)}}function n(t){try{l(i.throw(t))}catch(t){a(t)}}function l(t){var e;t.done?o(t.value):((e=t.value)instanceof r?e:new r(function(t){t(e)})).then(s,n)}l((i=i.apply(t,e||[])).next())})};import*as t from"echarts/core";import{GridComponent as e,DataZoomComponent as r,TooltipComponent as i}from"echarts/components";import{LineChart as o}from"echarts/charts";import{UniversalTransition as a}from"echarts/features";import{CanvasRenderer as s}from"echarts/renderers";import n from"lodash.debounce";import{css as l,html as h,LitElement as d,unsafeCSS as p}from"lit";import{customElement as c,property as u,query as m}from"lit/decorators.js";import{i18next as y,translate as b}from"@openremote/or-translate";import{AssetModelUtil as _}from"@openremote/model";import g,{DefaultColor2 as f,DefaultColor3 as v,DefaultColor4 as T}from"@openremote/core";import{InputType as O}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-components/or-panel";import"@openremote/or-chart";import{JSONPath as w}from"jsonpath-plus";import A from"moment";import{isAxiosError as x}from"@openremote/rest";import{styleMap as H}from"lit/directives/style-map.js";import{when as P}from"lit/directives/when.js";t.use([e,i,r,o,s,a]);export class OrAttributeHistoryEvent extends CustomEvent{constructor(t,e){super(OrAttributeHistoryEvent.NAME,{detail:{value:t,previousValue:e},bubbles:!0,composed:!0})}}OrAttributeHistoryEvent.NAME="or-attribute-history-event";let tableStyle=require("@material/data-table/dist/mdc.data-table.css"),style=l`
    :host {
        --internal-or-attribute-history-background-color: var(--or-attribute-history-background-color, var(--or-app-color2, ${p(f)}));
        --internal-or-attribute-history-text-color: var(--or-attribute-history-text-color, var(--or-app-color3, ${p(v)}));
        --internal-or-attribute-history-controls-margin: var(--or-attribute-history-controls-margin, 10px 0);
        --internal-or-attribute-history-controls-justify-content: var(--or-attribute-history-controls-justify-content, flex-end);
        --internal-or-attribute-history-graph-fill-color: var(--or-attribute-history-graph-fill-color, var(--or-app-color4, ${p(T)}));       
        --internal-or-attribute-history-graph-fill-opacity: var(--or-attribute-history-graph-fill-opacity, 0.25);       
        --internal-or-attribute-history-graph-line-color: var(--or-attribute-history-graph-line-color, var(--or-app-color4, ${p(T)}));       
        --internal-or-attribute-history-graph-point-color: var(--or-attribute-history-graph-point-color, var(--or-app-color4, ${p(T)}));
        --internal-or-attribute-history-graph-point-border-color: var(--or-attribute-history-graph-point-border-color, var(--or-app-color4, ${p(T)}));
        --internal-or-attribute-history-graph-point-radius: var(--or-attribute-history-graph-point-radius, 2);
        --internal-or-attribute-history-graph-point-hit-radius: var(--or-attribute-history-graph-point-hit-radius, 20);       
        --internal-or-attribute-history-graph-point-border-width: var(--or-attribute-history-graph-point-border-width, 2);
        --internal-or-attribute-history-graph-point-hover-color: var(--or-attribute-history-graph-point-hover-color, var(--or-app-color4, ${p(T)}));
        --internal-or-attribute-history-graph-point-hover-border-color: var(--or-attribute-history-graph-point-hover-border-color, var(--or-app-color4, ${p(T)}));
        --internal-or-attribute-history-graph-point-hover-radius: var(--or-attribute-history-graph-point-hover-radius, 4);      
        --internal-or-attribute-history-graph-point-hover-border-width: var(--or-attribute-history-graph-point-hover-border-width, 2);
        display: block;                
    }
    
    :host([hidden]) {
        display: none;
    }
    
    #container {
        position: relative;
        display: flex;
        min-width: 0;
        width: 100%;
        height: 100%;
        flex-direction: column;
    }
       
    .button-icon {
        align-self: center;
        padding: 10px;
        cursor: pointer;
    }


    #msg {
        height: 100%;
        width: 100%;
        justify-content: center;
        align-items: center;
        text-align: center;
    }
    
    #msg:not([hidden]) {
        display: flex;    
    }
    
    #controls {
        display: flex;
        flex-wrap: wrap;
        justify-content: var(--internal-or-attribute-history-controls-justify-content);
        margin: var(--internal-or-attribute-history-controls-margin);        
        flex-direction: row;
    }
    
    #time-picker {
        width: 130px;
        padding: 0 5px;
    }

    #ending-controls {
        max-width: 100%;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }
    
    #ending-controls > * {
        padding: 0 3px;
    }
    
    #ending-date {
        width: 220px;
        padding-left: 5px;
    }
    
    #chart {
        width: 100%;
        height: 100%;
    }
    
    #chart-container {
        position: relative;
        min-height: 350px;
    }
        
    #table-container {
        height: 100%;
        min-height: 250px;
    }
    
    #table {
        width: 100%;
        margin-bottom: 10px;
    }
    
    #table > table {
        width: 100%;
        table-layout: fixed;
    }
    
    #table th, #table td {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
`,OrAttributeHistory=OrAttributeHistory_1=class extends b(y)(d){constructor(){super(...arguments),this.period="day",this._loading=!1,this._chartOptions={},this._zoomChanged=!1,this._zoomReset=!1,this._dataFirstLoaded=!1}static get styles(){return[l`${p(tableStyle)}`,style]}connectedCallback(){super.connectedCallback(),this._style=window.getComputedStyle(this)}disconnectedCallback(){super.disconnectedCallback(),this._cleanup()}shouldUpdate(t){var e;let r=t.has("period")||t.has("toTimestamp")||t.has("attribute");return(!this._dataFirstLoaded||!!t.get("_loading")||!!r)&&(this.toTimestamp?(t.has("attribute")&&this._cleanup(),!this._type&&this.attribute&&(this._type=_.getValueDescriptor(this.attribute.type)||{}),r&&(this._type=void 0,this._data=void 0,this._loadData(),this._zoomReset=!0,null==(e=this._chart)||e.dispatchAction({type:"dataZoom",start:0,end:100})),super.shouldUpdate(t)):(this.toTimestamp=new Date,!1))}render(){let t=this._type&&("number"===this._type.jsonType||"boolean"===this._type.jsonType),e=!this._type;return h`
            <div id="container">
                <div id="controls">
                    <or-mwc-input id="time-picker" .type="${O.SELECT}" ?disabled="${e}" .label="${y.t("timeframe")}" @or-mwc-input-changed="${t=>this.period=t.detail.value}" .value="${this.period}" .options="${this._getPeriodOptions()}"></or-mwc-input>
                    <div id="ending-controls">
                        <or-mwc-input id="ending-date" .type="${O.DATETIME}" ?disabled="${e}" label="${y.t("ending")}" .value="${this.toTimestamp}" @or-mwc-input-changed="${t=>this._updateTimestamp(A(t.detail.value).toDate())}"></or-mwc-input>
                        <or-icon class="button button-icon" ?disabled="${e}" icon="chevron-left" @click="${()=>this._updateTimestamp(this.toTimestamp,!1,0)}"></or-icon>
                        <or-icon class="button button-icon" ?disabled="${e}" icon="chevron-right" @click="${()=>this._updateTimestamp(this.toTimestamp,!0,0)}"></or-icon>
                        <or-icon class="button button-icon" ?disabled="${e}" icon="chevron-double-right" @click="${()=>this._updateTimestamp(new Date)}"></or-icon>
                    </div>
                </div>
                
                ${P(!this._type,()=>h`
                    <div id="msg">
                        <or-translate value="invalidAttribute"></or-translate>
                    </div>
                `,()=>P(this._error,()=>h`
                    <div id="msg">
                        <or-translate .value="${this._error}"></or-translate>
                    </div>
                `,()=>P(t,()=>h`
                    
                    ${P(this._loading&&!this._data,()=>h`
                        <or-loading-indicator style="position: absolute; top: 50%; left: 50%;"></or-loading-indicator>
                    `)}
                    <div id="chart-container" style="${this._loading?"opacity: 0.7":void 0}">
                        <div id="chart"></div>
                    </div>
                    
                `,()=>h`

                    <div id="table-container">
                        ${P(this._loading,()=>h`
                            <or-loading-indicator></or-loading-indicator>
                        `,()=>this._tableTemplate)}
                    </div>
                `)))}
            </div>
        `}willUpdate(e){if(super.willUpdate(e),this._type&&this._data){if(this._type&&("number"===this._type.jsonType||"boolean"===this._type.jsonType)){let r=this._data.map(t=>[t.x,t.y]);if(this._chart)e.has("_data")&&this._updateChartData();else{let e=this._style.getPropertyValue("--internal-or-attribute-history-graph-fill-color").trim(),i=Number(this._style.getPropertyValue("--internal-or-attribute-history-graph-fill-opacity").trim());!isNaN(i)&&(e.startsWith("#")&&(4===e.length||7===e.length)?e+=4===e.length?Math.round(255*i).toString(16).substr(0,1):Math.round(255*i).toString(16):e.startsWith("rgb(")&&(e=e.substring(0,e.length-1)+i)),this._chartOptions={animation:!1,grid:{show:!0,backgroundColor:this._style.getPropertyValue("--internal-or-asset-viewer-panel-color"),borderColor:this._style.getPropertyValue("--internal-or-attribute-history-text-color"),left:4,right:4,top:10,containLabel:!0},backgroundColor:this._style.getPropertyValue("--internal-or-asset-viewer-panel-color"),tooltip:{trigger:"axis",confine:!0,axisPointer:{type:"cross"},formatter:t=>{if(Array.isArray(t)&&t.length>0){let e=t[0].value[1];return void 0!==e?e.toString():""}return""}},xAxis:{type:"time",axisLine:{onZero:!1,lineStyle:{color:this._style.getPropertyValue("--internal-or-attribute-history-text-color")}},splitLine:{show:!0},min:this._startOfPeriod,max:this._endOfPeriod,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-attribute-history-text-color")}},boundaryGap:["10%","10%"],scale:!0},dataZoom:[{type:"inside",start:0,end:100},{type:"slider",start:0,end:100,showDataShadow:!1,backgroundColor:e,fillerColor:e,moveHandleStyle:{color:this._style.getPropertyValue("--internal-or-attribute-history-graph-fill-color")},emphasis:{moveHandleStyle:{color:this._style.getPropertyValue("--internal-or-attribute-history-graph-fill-color")},handleLabel:{show:!0}},handleLabel:{show:!1},showDetail:!1}],series:[{name:"timestamp    value",type:"line",showSymbol:r.length<=30,data:r,sampling:"lttb",itemStyle:{color:this._style.getPropertyValue("--internal-or-attribute-history-graph-line-color")}}]},this._chart=t.init(this._chartElem),this._chart.setOption(this._chartOptions),window.addEventListener("resize",()=>{var t;return null==(t=this._chart)?void 0:t.resize()}),new ResizeObserver(()=>{var t;return null==(t=this._chart)?void 0:t.resize()}).observe(this._chartElem),this._chart.on("datazoom",n(t=>{this._onZoomChange(t)},750))}}else(!this._tableTemplate||e.has("_data"))&&(this._tableTemplate=this._getTableTemplate());this.onCompleted().then(()=>{this.dispatchEvent(new OrAttributeHistoryEvent("rendered"))})}}onCompleted(){return __awaiter(this,void 0,void 0,function*(){yield this.updateComplete})}_cleanup(){this._tableTemplate=void 0,this._chart&&(this._chart.dispose(),this._chart=void 0),this._table&&(this._table.destroy(),this._table=void 0)}_getTableTemplate(){let t=this.assetType,e=this.attribute?this.attribute.name:this.attributeRef?this.attributeRef.name:void 0,r=this.attribute?this.attribute.type:void 0;if(!this._data||!t||!e||!r)return h``;let i={autoColumns:!0};if(this.config&&this.config.table&&(this.config.table.assetTypes&&this.config.table.assetTypes[t]&&(this.config.table.assetTypes[t].attributeNames&&this.config.table.assetTypes[t].attributeNames[e]||r&&this.config.table.assetTypes[t].attributeValueTypes&&this.config.table.assetTypes[t].attributeValueTypes[r])?i=this.config.table.assetTypes[t].attributeNames&&this.config.table.assetTypes[t].attributeNames[e]||this.config.table.assetTypes[t].attributeValueTypes[r]:this.config.table.attributeNames&&this.config.table.attributeNames[e]?i=this.config.table.attributeNames[e]:r&&this.config.table.attributeValueTypes&&this.config.table.attributeValueTypes[r]?i=this.config.table.attributeValueTypes[r]:this.config.table.default&&(i=this.config.table.default),i||(i={autoColumns:!0})),i.autoColumns){(i=Object.assign({},i)).columns=[];let t=this._data.find(t=>void 0!==t.y);t&&("object"!=typeof t.y||Array.isArray(t.y)?i.columns.push({type:"prop",header:"value",stringify:"object"==typeof t.y,numeric:"number"==typeof t.y}):i.columns=Object.entries(t.y).map(([t,e])=>({type:"prop",header:t,path:"$.['"+t+"']",stringify:"object"==typeof e,numeric:!isNaN(Number(e))}))),i.columns.length>0&&i.columns.push({header:"timestamp",type:"timestamp"})}return i.columns&&i.columns.length>0?h`
            <div id="table" class="mdc-data-table">
                <table style="${i.styles?H(i.styles):""}" class="mdc-data-table__table" aria-label="${e+" history"}">
                    <thead>
                        <tr class="mdc-data-table__header-row">
                            ${i.columns.map(t=>h`<th style="${t.headerStyles?H(t.headerStyles):""}" class="mdc-data-table__header-cell ${t.numeric?"mdc-data-table__header-cell--numeric":""}" role="columnheader" scope="col"><or-translate value="${t.header}"></or-translate></th>`)}
                        </tr>
                    </thead>
                    <tbody class="mdc-data-table__content">
                        ${this._data.map(t=>h`
                                <tr class="mdc-data-table__row">
                                    ${i.columns.map(e=>{let r=this._getCellValue(t,e,i.timestampFormat);return h`<td style="${e.styles?H(e.styles):""}" class="mdc-data-table__cell ${e.numeric?"mdc-data-table__cell--numeric":""}" title="${r}">${r}</td>`})}
                                </tr>
                            `)}
                    </tbody>
                </table>
            </div>
            `:(console.warn("OrAttributeHistory: No columns configured so nothing to show"),h``)}_getCellValue(t,e,r){switch(e.type){case"timestamp":let i=A(t.x).format(r||OrAttributeHistory_1.DEFAULT_TIMESTAMP_FORMAT);if(e&&e.contentProvider){let r=e.contentProvider(t,i,e);if(r)return r}return i;case"prop":let o=t.y;if(e.path&&Array.isArray(o=w({path:e.path,json:t.y,wrap:!1}))&&1===o.length&&(o=o[0]),e&&e.contentProvider){let r=e.contentProvider(t,o,e);if(r)return r}if(e.stringify)return JSON.stringify(o);return o}}_getIntervalOptions(){return["HOUR","DAY","WEEK","MONTH","YEAR"].map(t=>[t,y.t(t.toLowerCase())])}_getPeriodOptions(){return["hour","day","week","month","year"]}_loadData(){return __awaiter(this,void 0,void 0,function*(){var t;if(this._data&&!this._zoomChanged||!this.assetType||!this.assetId||!this.attribute&&!this.attributeRef||!this.period||!this.toTimestamp)return;if(this._loading)if(!this._dataAbortController)return;else this._dataAbortController.abort("Data request overridden"),delete this._dataAbortController;this._error=void 0,this._loading=!0;let e=this.assetId,r=this.attribute?this.attribute.name:this.attributeRef.name;this._dataAbortController=new AbortController;try{let t;if(!this._type){let t=this.attribute;if(!t){let i=yield g.rest.api.AssetResource.queryAssets({ids:[e],select:{attributes:[r]}},{signal:this._dataAbortController.signal});200===i.status&&i.data.length>0&&(t=i.data[0].attributes?i.data[0].attributes[r]:void 0)}t&&(this._type=_.getValueDescriptor(t.type)||{})}if(!this._type||!this._type.name){this._loading=!1;return}let i="HOUR";switch(this.period){case"hour":i="MINUTE";break;case"day":case"week":i="HOUR";break;case"month":i="DAY";break;case"year":i="MONTH"}let o=i.toLowerCase();this._zoomChanged||(this._startOfPeriod=A(this.toTimestamp).subtract(1,this.period).startOf(o).add(1,o).toDate().getTime(),this._endOfPeriod=A(this.toTimestamp).startOf(o).add(1,o).toDate().getTime(),this._queryStartOfPeriod=this._startOfPeriod,this._queryEndOfPeriod=this._endOfPeriod),t=this._type&&("number"===this._type.jsonType||"boolean"===this._type.jsonType)?yield g.rest.api.AssetDatapointResource.getDatapoints(e,r,{type:"lttb",fromTimestamp:this._queryStartOfPeriod,toTimestamp:this._queryEndOfPeriod,amountOfPoints:100},{signal:this._dataAbortController.signal}):yield g.rest.api.AssetDatapointResource.getDatapoints(e,r,{type:"all",fromTimestamp:this._startOfPeriod,toTimestamp:this._endOfPeriod},{signal:this._dataAbortController.signal}),this._loading=!1,this._zoomChanged=!1,200===t.status&&(this._data=t.data.filter(t=>null!==t.y&&void 0!==t.y).map(t=>({x:t.x,y:t.y})))}catch(e){if(console.error(e),(null==e?void 0:e.message)==="canceled")return;if(this._loading=!1,x(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="errorOccurred"}})}_updateTimestamp(t,e,r=300){this._updateTimestampTimer&&(window.clearTimeout(this._updateTimestampTimer),this._updateTimestampTimer=void 0),this._updateTimestampTimer=window.setTimeout(()=>{let r=A(t);void 0!==e&&r.add(e?1:-1,this.period),this.toTimestamp=r.toDate()},r)}_onZoomChange(t){var e,r;if(!this._zoomReset){this._zoomChanged=!0;let{start:i,end:o}=null!=(r=null==(e=t.batch)?void 0:e[0])?r:t;this._queryStartOfPeriod=this._startOfPeriod+(this._endOfPeriod-this._startOfPeriod)*i/100,this._queryEndOfPeriod=this._startOfPeriod+(this._endOfPeriod-this._startOfPeriod)*o/100,this._loadData().then(()=>{this._updateChartData()})}this._zoomReset=!1}_updateChartData(){let t=this._data.map(t=>[t.x,t.y]);this._chart.setOption({xAxis:{min:this._startOfPeriod,max:this._endOfPeriod},series:[{data:t,showSymbol:t.length<=30}]})}};OrAttributeHistory.DEFAULT_TIMESTAMP_FORMAT="L HH:mm:ss",__decorate([u({type:String})],OrAttributeHistory.prototype,"assetType",void 0),__decorate([u({type:String})],OrAttributeHistory.prototype,"assetId",void 0),__decorate([u({type:Object})],OrAttributeHistory.prototype,"attribute",void 0),__decorate([u({type:Object})],OrAttributeHistory.prototype,"attributeRef",void 0),__decorate([u({type:String})],OrAttributeHistory.prototype,"period",void 0),__decorate([u({type:Number})],OrAttributeHistory.prototype,"toTimestamp",void 0),__decorate([u({type:Object})],OrAttributeHistory.prototype,"config",void 0),__decorate([u()],OrAttributeHistory.prototype,"_loading",void 0),__decorate([u()],OrAttributeHistory.prototype,"_data",void 0),__decorate([u()],OrAttributeHistory.prototype,"_tableTemplate",void 0),__decorate([m("#chart")],OrAttributeHistory.prototype,"_chartElem",void 0),__decorate([m("#table")],OrAttributeHistory.prototype,"_tableElem",void 0),OrAttributeHistory=OrAttributeHistory_1=__decorate([c("or-attribute-history")],OrAttributeHistory);export{OrAttributeHistory};