var __decorate=this&&this.__decorate||function(e,t,r,i){var s,a=arguments.length,l=a<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)l=Reflect.decorate(e,t,r,i);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(l=(a<3?s(l):a>3?s(t,r,l):s(t,r))||l);return a>3&&l&&Object.defineProperty(t,r,l),l},__awaiter=this&&this.__awaiter||function(e,t,r,i){return new(r||(r=Promise))(function(s,a){function l(e){try{n(i.next(e))}catch(e){a(e)}}function o(e){try{n(i.throw(e))}catch(e){a(e)}}function n(e){var t;e.done?s(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(l,o)}n((i=i.apply(e,t||[])).next())})};import{css as e,html as t,LitElement as r}from"lit";import{customElement as i,property as s,query as a}from"lit/decorators.js";import{OrRulesRequestSaveEvent as l,OrRulesRuleChangedEvent as o,OrRulesRuleUnsupportedEvent as n,OrRulesSaveEvent as d,RuleViewInfoMap as u}from"./index";import c,{Util as h}from"@openremote/core";import"./json-viewer/or-rule-json-viewer";import"./or-rule-text-viewer";import{project as p}from"./flow-viewer/components/flow-editor";import{INTUITIVE_NOT_APPLICABLE as v}from"@openremote/or-scheduler";import{InputType as m}from"@openremote/or-mwc-components/or-mwc-input";import{i18next as y,translate as f}from"@openremote/or-translate";import{showErrorDialog as g}from"@openremote/or-mwc-components/or-mwc-dialog";import{when as R}from"lit/directives/when.js";let DISABLED_RRULE_PARTS=["interval","bymonth","byweekno","byyearday","byhour","byminute","bysecond","count"];export const style=e`

    :host {
        display: block;
        height: 100%;
        width: 100%;
        overflow-y: auto;
    }

    or-scheduler {
        margin-left: 10px;
        margin-right: 20px;
        max-width: 400px;
    }

    .wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 100%;
    }

    #main-wrapper.saving {
        opacity: 0.5;
        pointer-events: none;
    }
    
    #rule-name {
        max-width: 400px;
        flex: 1 1 0;
        display: flex;
    }
    
    #rule-header {
        display: flex;
        align-items: center;
        width: 100%;
        box-sizing: border-box;
        min-height: var(--internal-or-rules-header-height);
        height: var(--internal-or-rules-header-height);
        z-index: 7;
        padding: 15px 20px;
        --or-icon-fill: var(--internal-or-rules-panel-color);
    }
    
    #rule-header-controls {
        margin-left: auto;
        display: flex;
        align-items: center;
    }
    
    #rule-id {
        margin-left: 10px;
        font-size: small;
    }
    
    #active-wrapper {
        display: flex;
        align-items: center;
    }
    
    #rule-view {
        flex-grow: 1;
        background-color: var(--internal-or-rules-background-color);
    }
    
    .iconfill-gray {
        margin-left: 10px;
        --or-icon-fill: var(--internal-or-rules-list-icon-color-ok);
    }

    .iconfill-red {
        margin-left: 10px;
        --or-icon-fill: var(--internal-or-rules-list-icon-color-error);
    }

    .legacy-warning {
        width: calc(100% - 40px);
        box-sizing: border-box;
        margin: 0 20px 15px;
        padding: 12px 14px;
        border-radius: 4px;
        border: 2px solid var(--internal-or-rules-invalid-color);
        color: var(--internal-or-rules-invalid-color);
    }
`;let OrRuleViewer=class extends f(y)(r){static get styles(){return[style]}constructor(){super(),this.readonly=!1,this.disabled=!1,this.modified=!1,this._ruleValid=!1,this._supported=!0,this._focusName=!1,this.addEventListener(o.NAME,this._onRuleChanged),this.addEventListener(n.NAME,this._onRuleUnsupported)}get valid(){return this.ruleset&&this.view&&this._ruleValid&&this.ruleset.name&&this.ruleset.name.length>=1&&this.ruleset.name.length<255}shouldUpdate(e){return e.has("ruleset")&&(this._supported=!0,this.modified=!1,this._ruleValid=!1,this.ruleset&&(this._focusName=!0,this.modified=!this.ruleset.id)),super.shouldUpdate(e)}render(){if(!this.ruleset)return t`<div class="wrapper" style="justify-content: center"><or-translate value="noRuleSelected"></or-translate></div>`;let e=this._isReadonly(),r=this._isLegacyJavascriptRuleset(),i=u[this.ruleset.lang].viewTemplateProvider(this.ruleset,this.config,e),s="help",a="iconfill-gray",l="NOSTATUS";switch(this.ruleset.status&&(l=this.ruleset.status),this.ruleset.status){case"DEPLOYED":s="play",a="iconfill-gray";break;case"READY":s="check",a="iconfill-gray";break;case"COMPILATION_ERROR":case"LOOP_ERROR":case"VALIDITY_PERIOD_ERROR":case"EXECUTION_ERROR":s="alert-octagon",a="iconfill-red",l=this.ruleset.error;break;case"DISABLED":s="minus-circle",a="iconfill-gray";break;case"PAUSED":s="calendar-arrow-right",a="iconfill-gray";break;case"EXPIRED":s="calendar-remove",a="iconfill-gray";break;case"REMOVED":s="close",a="iconfill-gray";break;default:s="stop",a="iconfill-gray",l="NOSTATUS"}return t`
            <div id="main-wrapper" class="wrapper">
                <div id="rule-header">
                    <or-mwc-input id="rule-name" outlined .type="${m.TEXT}" .label="${y.t("ruleName")}" ?focused="${this._focusName}" .value="${this.ruleset?this.ruleset.name:null}" ?disabled="${e}" required minlength="1" maxlength="255" @or-mwc-input-changed="${e=>this._changeName(e.detail.value)}"></or-mwc-input>
                    <or-icon class="${a}" title="${y.t("rulesetStatus."+l)}" icon="${s}"></or-icon>
                    <span id="rule-id">${this.ruleset.id?"ID: "+this.ruleset.id:""}</span>
                    <div id="rule-header-controls">
                        <span id="active-wrapper">
                            <or-translate value="enabled"></or-translate>
                            <or-mwc-input .type="${m.CHECKBOX}" .value="${this.ruleset&&this.ruleset.enabled}" ?disabled="${e||!this.ruleset.id}" @or-mwc-input-changed="${this._toggleEnabled}"></or-mwc-input>
                        </span>
                        ${R(!e,()=>{var e,r;return t`
                            <or-scheduler
                                    id="rule-header-validity"
                                    header="scheduleRuleActivity"
                                    defaultEventTypeLabel="validityAlways"
                                    disableNegativeByPartValues
                                    .disabledRRuleParts="${DISABLED_RRULE_PARTS}"
                                    .disabledByPartCombinations="${v}"
                                    .schedule="${null==(r=null==(e=this.ruleset)?void 0:e.meta)?void 0:r.validity}"
                                    @or-scheduler-changed="${this._onSchedulerChanged}"
                            ></or-scheduler>
                        `})}
                        <or-mwc-input .type="${m.BUTTON}" id="save-btn" label="save" raised ?disabled="${this._cannotSave()}" @or-mwc-input-changed="${this._onSaveClicked}"></or-mwc-input>
                    </div>
                </div>

                ${R(r,()=>t`
                    <div class="legacy-warning">
                        <or-translate value="rulesLegacyJavaScriptWarning"></or-translate>
                    </div>
                `)}
                
                ${i}
            </div>
        `}updated(e){(e.has("ruleset")||e.has("modified"))&&this.ruleset&&this.view&&(this._ruleValid=this.view.validate())}_isReadonly(){return this.readonly||this._isLegacyJavascriptRuleset()||!c.hasRole("write:rules")}_cannotSave(){return this._isReadonly()||!this.ruleset||!this.modified||!this.valid}_isLegacyJavascriptRuleset(e=this.ruleset){return(null==e?void 0:e.lang)==="JAVASCRIPT"}_changeName(e){!this._isReadonly()&&this.ruleset&&this.ruleset.name!==e&&(this.ruleset.name=e,this.modified=!0,this.requestUpdate())}_onSchedulerChanged(e){var t;!this._isReadonly()&&this.ruleset&&(null!=(t=this.ruleset).meta||(t.meta={}),this.ruleset.meta.validity=null==e?void 0:e.detail.value,this.modified=!0,this.requestUpdate())}_onRuleChanged(e){this._isReadonly()||(this.modified=!0),this._ruleValid=e.detail}_onSaveClicked(){if(this._isReadonly()){this._isLegacyJavascriptRuleset()&&g(y.t("rulesLegacyJavaScriptWarning"));return}this.ruleset&&this.view&&(p.emit("fitview"),(!this.config||!this.config.rulesetSaveHandler||this.config.rulesetSaveHandler(this.ruleset))&&h.dispatchCancellableEvent(this,new l(this.ruleset)).then(e=>{e.allow&&this._doSave()}))}_doSave(){return __awaiter(this,void 0,void 0,function*(){let e,t=this.ruleset;if(!t||!this.view)return;if(this._isReadonly()){this._isLegacyJavascriptRuleset(t)&&g(y.t("rulesLegacyJavaScriptWarning"));return}let r=!1,i=!t.id;this.saveBtnElem.disabled=!0,this.wrapperElem.classList.add("saving"),this.view.beforeSave();try{switch(t.type){case"asset":e=i?yield c.rest.api.RulesResource.createAssetRuleset(t):yield c.rest.api.RulesResource.updateAssetRuleset(t.id,t);break;case"realm":e=i?yield c.rest.api.RulesResource.createRealmRuleset(t):yield c.rest.api.RulesResource.updateRealmRuleset(t.id,t);break;case"global":e=i?yield c.rest.api.RulesResource.createGlobalRuleset(t):yield c.rest.api.RulesResource.updateGlobalRuleset(t.id,t)}if(e.status!==(i?200:204)){r=!0,g("Create ruleset returned unexpected status: "+e.status);return}e.data&&(t.id=e.data)}catch(e){r=!0,console.error("Failed to save ruleset",e)}this.wrapperElem.classList.remove("saving"),this.saveBtnElem.disabled=!1,r&&g(y.t("saveRulesetFailed")),this.dispatchEvent(new d({ruleset:t,isNew:i,success:!r}))})}_onRuleUnsupported(){this._supported=!1}_toggleEnabled(){!this._isReadonly()&&this.ruleset&&(this.ruleset.enabled=!this.ruleset.enabled,this.modified=!0,this.requestUpdate())}};__decorate([s({type:Object})],OrRuleViewer.prototype,"ruleset",void 0),__decorate([s({type:Boolean})],OrRuleViewer.prototype,"readonly",void 0),__decorate([s({type:Boolean})],OrRuleViewer.prototype,"disabled",void 0),__decorate([s({type:Object})],OrRuleViewer.prototype,"config",void 0),__decorate([s({attribute:!1})],OrRuleViewer.prototype,"modified",void 0),__decorate([s({attribute:!1})],OrRuleViewer.prototype,"_ruleValid",void 0),__decorate([s({attribute:!1})],OrRuleViewer.prototype,"_supported",void 0),__decorate([a("#rule-view")],OrRuleViewer.prototype,"view",void 0),__decorate([a("#main-wrapper")],OrRuleViewer.prototype,"wrapperElem",void 0),__decorate([a("#save-btn")],OrRuleViewer.prototype,"saveBtnElem",void 0),OrRuleViewer=__decorate([i("or-rule-viewer")],OrRuleViewer);export{OrRuleViewer};