var OrLogViewer_1,__decorate=this&&this.__decorate||function(e,t,i,a){var o,r=arguments.length,s=r<3?t:null===a?a=Object.getOwnPropertyDescriptor(t,i):a;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,a);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},__awaiter=this&&this.__awaiter||function(e,t,i,a){return new(i||(i=Promise))(function(o,r){function s(e){try{n(a.next(e))}catch(e){r(e)}}function l(e){try{n(a.throw(e))}catch(e){r(e)}}function n(e){var t;e.done?o(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(s,l)}n((a=a.apply(e,t||[])).next())})};import{css as e,html as t,LitElement as i,unsafeCSS as a}from"lit";import{customElement as o,property as r,query as s}from"lit/decorators.js";import{i18next as l,translate as n}from"@openremote/or-translate";import*as c from"@openremote/model";import d,{DefaultColor2 as h,DefaultColor3 as p,DefaultColor4 as g,DefaultColor5 as m,Util as _}from"@openremote/core";import{InputType as u}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-components/or-panel";import v from"moment";import{getContentWithMenuTemplate as w}from"@openremote/or-mwc-components/or-mwc-menu";import{showSnackbar as b}from"@openremote/or-mwc-components/or-mwc-snackbar";import{when as y}from"lit/directives/when.js";let linkParser=require("http-link-header"),tableStyle=require("@material/data-table/dist/mdc.data-table.css"),style=e`
    :host {
        --internal-or-log-viewer-background-color: var(--or-log-viewer-background-color, var(--or-app-color2, ${a(h)}));
        --internal-or-log-viewer-text-color: var(--or-log-viewer-text-color, var(--or-app-color3, ${a(p)}));
        --internal-or-log-viewer-controls-margin: var(--or-log-viewer-controls-margin, 0);
        
        display: block;                
    }
    
    :host([hidden]) {
        display: none;
    }
    
    #container {
        display: flex;
        min-width: 0;
        width: 100%;
        height: 100%;
        flex-direction: column;
    }
       
    #msg {
        height: 100%;
        width: 100%;
        justify-content: center;
        align-items: center;
        text-align: center;
    }
    
    #msg:not([hidden]) {
        display: flex;    
    }
    
    #controls {
        flex: 0;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        margin: var(--internal-or-log-viewer-controls-margin);
        padding: 0 20px 20px 20px;
    }
    
    #controls > * {
        margin-top: 20px;
    }
    
    #time-controls {
        display: flex;
        align-items: center;
    }
    
    #live-button {
        margin-right: 40px;
    }
    
/*  min-width of selects is 200px somehow
    #period-select {
        width: 90px;
    }
    
    #level-select {
        width: 120px;
    }
    
    #limit-select {
        width: 80px;
    }
*/
    
    #log-controls, #ending-controls, #page-controls {
        display: flex;
        max-width: 100%;
        align-items: center;
    }
    
    #ending-controls {
        float: right;
        margin: 0 10px;
    }
    
    #log-controls > *, #ending-controls > *, #page-controls > * {
        padding: 0 5px;
    }
        
    #page-controls[hidden] {
        visibility: hidden;
    }
    
    #ending-date {
        min-width: 0;
    }
    
    #table-container {
        height: 100%;
        overflow: auto;
    }
    
    #table {
        width: 100%;
        margin-bottom: 10px;
    }
    
    #table > table {
        width: 100%;
        table-layout: fixed;
    }
    
    #table th:not(.icon-cell), #table td:not(.icon-cell) {
        word-wrap: break-word;
        white-space: pre-wrap;
    }
    
    .copy-button {
        --or-mwc-input-color: var(--or-app-color5, ${a(m)});
    }
    
    .copy-button:hover {
        --or-mwc-input-color: var(--or-app-color4, ${a(g)});
    }
`,OrLogViewer=OrLogViewer_1=class extends n(l)(i){constructor(){super(...arguments),this.live=!1,this._loading=!1,this._currentPage=1}static get styles(){return[e`${a(tableStyle)}`,style]}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this._cleanup(),this._unsubscribeEvents()}shouldUpdate(e){return(e.has("level")||e.has("interval")||e.has("timestamp")||e.has("limit")||e.has("categories")||e.has("filter")||e.has("live"))&&!this.live&&(this._pageCount=void 0,this._currentPage=1,this._data=void 0),this.interval||(this.interval=OrLogViewer_1.DEFAULT_INTERVAL),!this.categories&&this.config&&this.config.initialCategories&&(this.categories=[...this.config.initialCategories]),void 0===this.filter&&this.config&&this.config.initialFilter&&(this.filter=this.config.initialFilter),this.level||(this.config&&this.config.initialLevel?this.level=this.config.initialLevel:this.level=OrLogViewer_1.DEFAULT_LEVEL),this.live||this.timestamp||(this.timestamp=new Date),this._data||this.live||this._loadData(),e.has("live")&&(this.live?this._subscribeEvents():this._unsubscribeEvents()),super.shouldUpdate(e)}render(){let e=this._loading,i=this.live,a=this.config&&this.config.hideCategories,o=this.config&&this.config.hideFilter,r=this.config&&this.config.hideLevel;return t`
            <div id="container">
                <div id="controls">
                    <div id="log-controls">
                        ${a?"":w(t`<or-mwc-input .type=${u.BUTTON} raised ?disabled="${e}" .label="${l.t("categories")}" icontrailing="chevron-down"></or-mwc-input>`,this._getCategoryMenuItems(),this.categories,e=>this._onCategoriesChanged(e),()=>this._onCategoriesClosed(),!0)}
                        <or-mwc-input ?hidden="${o}" .type="${u.TEXT}" outlined ?disabled="${e}" icontrailing="magnify" .label="${l.t("subCategoryFilters")}" .value="${this.filter}" @or-mwc-input-changed="${e=>this._onFilterChanged(e.detail.value)}"></or-mwc-input>
                        <or-mwc-input ?hidden="${r}" .type="${u.SELECT}" id="level-select" ?disabled="${e}" .label="${l.t("level")}" @or-mwc-input-changed="${e=>this._onLevelChanged(e.detail.value)}" .value="${this.level}" .options="${this._getLevelOptions()}"></or-mwc-input>
                        <or-mwc-input .type="${u.SELECT}" id="limit-select" ?disabled="${e}" .label="${l.t("limit")}" @or-mwc-input-changed="${e=>this._onLimitChanged(e.detail.value)}" .value="${""+this.getLimit()}" .options="${this._getLimitOptions()}"></or-mwc-input>
                    </div>
                    <div id="page-controls" ?hidden="${i||!this._pageCount||!this._data||0===this._data.length}">
                        <or-mwc-input class="button" .type="${u.BUTTON}" ?disabled="${e||i||1===this._currentPage}" icon="chevron-left" @or-mwc-input-changed="${()=>this._updatePage(!1)}"></or-mwc-input>
                        <span>${this._currentPage}</span><or-translate value="of"></or-translate><span>${this._pageCount}</span>
                        <or-mwc-input class="button" .type="${u.BUTTON}" ?disabled="${e||i||this._currentPage===this._pageCount||this._data&&this._data.length<this.getLimit()}" icon="chevron-right" @or-mwc-input-changed="${()=>this._updatePage(!0)}"></or-mwc-input>
                    </div>
                    <div id="time-controls">
                        <or-mwc-input id="live-button" .type="${u.CHECKBOX}" ?disabled="${e}" .label="${l.t("live")}" @or-mwc-input-changed="${e=>this._onLiveChanged(e.detail.value)}" .value="${this.live}"></or-mwc-input>
                        <or-mwc-input .type="${u.SELECT}" id="period-select" ?disabled="${e||i}" .label="${l.t("period")}" @or-mwc-input-changed="${e=>this.interval=e.detail.value}" .value="${this.interval}" .options="${this._getIntervalOptions()}"></or-mwc-input>
                        <div id="ending-controls">
                            <or-mwc-input class="button" .type="${u.BUTTON}" ?disabled="${e||i}" icon="chevron-left" @or-mwc-input-changed="${()=>this.timestamp=this._calculateTimestamp(this.timestamp,!1)}"></or-mwc-input>
                            <or-mwc-input id="ending-date" .type="${u.DATETIME}" ?disabled="${e||i}" label="${l.t("ending")}" .value="${this.timestamp}" @or-mwc-input-changed="${e=>this.timestamp=this._calculateTimestamp(v(e.detail.value).toDate())}"></or-mwc-input>
                            <or-mwc-input class="button" .type="${u.BUTTON}" ?disabled="${e||i}" icon="chevron-right" @or-mwc-input-changed="${()=>this.timestamp=this._calculateTimestamp(this.timestamp,!0)}"></or-mwc-input>
                            <or-mwc-input class="button" .type="${u.BUTTON}" ?disabled="${e||i}" icon="chevron-double-right" @or-mwc-input-changed="${()=>this.timestamp=this._calculateTimestamp(new Date)}"></or-mwc-input>
                        </div>
                    </div>
                </div>
                
                ${e?t`<div id="msg">${l.t("loading")}</div>`:t`<div id="table-container">
                        ${this._data?this._getTable():""}
                    </div>`}
            </div>
        `}_getLimitOptions(){return["25","50","100","200"]}_getLevelOptions(){return Object.keys(c.SyslogLevel).map(e=>[e,l.t(e.toLocaleLowerCase())])}_getCategoryMenuItems(){return(this.config&&this.config.allowedCategories?this.config.allowedCategories:Object.keys(c.SyslogCategory)).map(e=>({text:l.t("logCategory."+e,{defaultValue:_.capitaliseFirstLetter(e.toLowerCase().replace(/_/g," "))}),value:e}))}getLimit(){return this.limit||OrLogViewer_1.DEFAULT_LIMIT}_onCategoriesChanged(e){this._pendingCategories=e}_onCategoriesClosed(){this._pendingCategories&&(this.categories=[...this._pendingCategories],this.categories&&this.live&&(this._data=this._data.filter(e=>this.categories.find(t=>t===e.category))),this._pendingCategories=void 0)}_onLiveChanged(e){this.live=e,e&&(this._data=[],this._pageCount=void 0,this._currentPage=1)}_onLimitChanged(e){if(!e){this.limit=void 0;return}this.limit=parseInt(e);let t=this.getLimit();this.live&&this._data.length>t&&this._data.splice(t-1)}_onFilterChanged(e){if(this.filter=e,this.filter&&this.live){let e=this.filter.split(";");this._data=this._data.filter(t=>e.find(e=>e===t.subCategory))}}_onLevelChanged(e){this.level=e,this.level&&this.live&&(this._data=this._data.filter(e=>this._eventMatchesLevel(e)))}_getTable(){return t`
            <div id="table" class="mdc-data-table">
                <table class="mdc-data-table__table" aria-label="logs list">
                    <thead>
                        <tr class="mdc-data-table__header-row">
                            <th style="width: 180px" class="mdc-data-table__header-cell" role="columnheader" scope="col">${l.t("timestamp")}</th>
                            <th style="width: 80px" class="mdc-data-table__header-cell" role="columnheader" scope="col">${l.t("level")}</th>
                            <th style="width: 130px" class="mdc-data-table__header-cell" role="columnheader" scope="col">${l.t("category")}</th>
                            <th style="width: 180px" class="mdc-data-table__header-cell" role="columnheader" scope="col">${l.t("subCategory")}</th>
                            <th style="width: 100%; min-width: 300px;" class="mdc-data-table__header-cell" role="columnheader" scope="col">${l.t("message")}</th>
                            <th style="width: 80px;" class="mdc-data-table__header-cell" role="columnheader" scope="col"></th>
                        </tr>
                    </thead>
                    <tbody class="mdc-data-table__content">
                        ${this._data.map(e=>t`
                                <tr class="mdc-data-table__row">
                                    <td class="mdc-data-table__cell">${v(e.timestamp).format(OrLogViewer_1.DEFAULT_TIMESTAMP_FORMAT)}</td>
                                    <td class="mdc-data-table__cell">${l.t(e.level)}</td>
                                    <td class="mdc-data-table__cell">${l.t(e.category)}</td>                                    
                                    <td class="mdc-data-table__cell">${l.t(e.subCategory)}</td>
                                    <td class="mdc-data-table__cell">${e.message}</td>
                                    <td class="mdc-data-table__cell icon-cell">
                                        ${y(window.isSecureContext,()=>t`
                                            <or-mwc-input type="${u.BUTTON}" class="copy-button" icon="content-copy" @or-mwc-input-changed=${()=>this._copyRow(e)}></or-mwc-input>
                                        `)}
                                    </td>
                                </tr>
                            `)}
                    </tbody>
                </table>
            </div>
            `}_copyRow(e){return __awaiter(this,void 0,void 0,function*(){try{let t=e.message||"";yield navigator.clipboard.writeText(t),b(void 0,l.t("copiedToClipboard"))}catch(e){console.error("Failed to copy:",e)}})}_getIntervalOptions(){return["HOUR","DAY","WEEK","MONTH","YEAR"].map(e=>[e,l.t(e.toLowerCase())])}_loadData(){return __awaiter(this,void 0,void 0,function*(){if(this._loading)return;this._loading=!0;let e=yield d.rest.api.SyslogResource.getEvents({level:this.level,per_page:this.getLimit(),page:this._currentPage,from:this._getFrom(),to:this.timestamp?this.timestamp.getTime():void 0,category:this.categories,subCategory:this.filter?this.filter.split(";"):void 0});this._loading=!1,200===e.status&&(this._data=e.data,this._pageCount=this._getPageCount(e))})}_getPageCount(e){let t=e.headers.link;if(t){let e=linkParser.parse(t).rel("last");if(Array.isArray(e)&&e.length>0&&(e=e[0]),e&&e.uri){let t=new URL(e.uri);return parseInt(_.getQueryParameters(t.search).page)}}}_updatePage(e){this._pageCount&&(e?this._currentPage<this._pageCount&&(this._data=void 0,this._currentPage++):this._currentPage>1&&(this._data=void 0,this._currentPage--))}_subscribeEvents(){return __awaiter(this,void 0,void 0,function*(){d.events&&(this._eventSubscriptionId=yield d.events.subscribe({eventType:"syslog"},e=>this._onEvent(e)))})}_unsubscribeEvents(){this._eventSubscriptionId&&(d.events.unsubscribe(this._eventSubscriptionId),this._eventSubscriptionId=void 0)}_getFrom(){if(this.timestamp&&this.interval)return this._calculateTimestamp(this.timestamp,!1).getTime()}_calculateTimestamp(e,t){if(!this.interval)return;let i=v(e);if(void 0!==t)switch(this.interval){case"HOUR":i.add(t?1:-1,"hour");break;case"DAY":i.add(t?1:-1,"day");break;case"WEEK":i.add(t?1:-1,"week");break;case"MONTH":i.add(t?1:-1,"month");break;case"YEAR":i.add(t?1:-1,"year")}return i.toDate()}_onEvent(e){if(this.categories&&!this.categories.find(t=>t===e.category)||this.filter&&!this.filter.split(";").find(t=>t===e.subCategory)||!this._eventMatchesLevel(e))return;let t=this.getLimit();this._data.length===t-1&&this._data.pop(),this._data.splice(0,0,e),this._refresh&&window.clearTimeout(this._refresh),this._refresh=window.setTimeout(()=>this.requestUpdate("_data"),2e3)}_eventMatchesLevel(e){return!this.level||"INFO"===this.level||"WARN"===this.level&&("WARN"===e.level||"ERROR"===e.level)||"ERROR"===this.level&&"ERROR"===e.level}_cleanup(){this._table&&(this._table.destroy(),this._table=void 0),this._refresh&&window.clearTimeout(this._refresh)}};OrLogViewer.DEFAULT_TIMESTAMP_FORMAT="L HH:mm:ss",OrLogViewer.DEFAULT_LIMIT=50,OrLogViewer.DEFAULT_LEVEL="INFO",OrLogViewer.DEFAULT_INTERVAL="HOUR",__decorate([r({type:String})],OrLogViewer.prototype,"interval",void 0),__decorate([r({type:Number})],OrLogViewer.prototype,"timestamp",void 0),__decorate([r({type:Number})],OrLogViewer.prototype,"limit",void 0),__decorate([r({type:Array})],OrLogViewer.prototype,"categories",void 0),__decorate([r({type:String})],OrLogViewer.prototype,"filter",void 0),__decorate([r({type:String})],OrLogViewer.prototype,"level",void 0),__decorate([r({type:Boolean})],OrLogViewer.prototype,"live",void 0),__decorate([r({type:Object})],OrLogViewer.prototype,"config",void 0),__decorate([r()],OrLogViewer.prototype,"_loading",void 0),__decorate([r()],OrLogViewer.prototype,"_data",void 0),__decorate([s("#table")],OrLogViewer.prototype,"_tableElem",void 0),OrLogViewer=OrLogViewer_1=__decorate([o("or-log-viewer")],OrLogViewer);export{OrLogViewer};