var OrRuleTree_1,__decorate=this&&this.__decorate||function(e,t,l,r){var s,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,l):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,l,r);else for(var n=e.length-1;n>=0;n--)(s=e[n])&&(o=(i<3?s(o):i>3?s(t,l,o):s(t,l))||o);return i>3&&o&&Object.defineProperty(t,l,o),o},__awaiter=this&&this.__awaiter||function(e,t,l,r){return new(l||(l=Promise))(function(s,i){function o(e){try{a(r.next(e))}catch(e){i(e)}}function n(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?s(e.value):((t=e.value)instanceof l?t:new l(function(e){e(t)})).then(o,n)}a((r=r.apply(e,t||[])).next())})};import{OrTreeMenu as e,TreeMenuSelection as t}from"@openremote/or-tree-menu";import{customElement as l,property as r,state as s}from"lit/decorators.js";import{css as i,html as o}from"lit";import n,{Util as a}from"@openremote/core";import{i18next as u}from"@openremote/or-translate";import{getContentWithMenuTemplate as d}from"@openremote/or-mwc-components/or-mwc-menu";import{InputType as c}from"@openremote/or-mwc-components/or-mwc-input";import{showOkCancelDialog as p}from"@openremote/or-mwc-components/or-mwc-dialog";import{OrRules as h,OrRulesAddEvent as g,OrRulesRequestAddEvent as R,OrRulesRequestDeleteEvent as m,OrRulesRequestGroupEvent as f,OrRulesRequestSelectionEvent as _,OrRulesSelectionEvent as v,RuleViewInfoMap as T}from"./index";import{ifDefined as O}from"lit/directives/if-defined.js";import{when as y}from"lit/directives/when.js";let styling=i`
    .iconfill-gray {
        --or-icon-fill: var(--internal-or-rules-list-icon-color-ok);
    }

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

    #rules-tree-global-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
        min-height: 48px;
        background: var(--or-app-color3, #4c4c4c);
        color: var(--or-app-color7, white);
        --or-icon-fill: var(--or-app-color7, white);
    }
`;export var RuleTreeSorting;!function(e){e.NAME="name",e.CREATED_ON="createdOn",e.LANGUAGE="language",e.STATUS="status"}(RuleTreeSorting||(RuleTreeSorting={}));let OrRuleTree=OrRuleTree_1=class extends e{constructor(){super(...arguments),this.global=!1,this.readonly=!1,this.nodes=[],this.draggable=!0,this.selection=t.MULTI,this.sortOptions=[RuleTreeSorting.NAME,RuleTreeSorting.CREATED_ON,RuleTreeSorting.STATUS,RuleTreeSorting.LANGUAGE],this.sortBy=RuleTreeSorting.NAME,this.groupFirst=!0,this.menuTitle="rules",this._loadingPromises=[],this._selectedTypes=new Set,this._cachedEmptyGroupNodes=[]}static get styles(){return[...super.styles,styling]}willUpdate(e){var l,r,s;if(e.has("rules"))if(this.rules){let e=this._getRuleNodes(this.rules),t=new Set(e.map(e=>e.id)),l=this._cachedEmptyGroupNodes.filter(e=>!t.has(e.id));this.nodes=[...e,...l],this._cachedEmptyGroupNodes=l}else this._loadRulesets(this.global).then(e=>this.rules=e);return e.has("nodes")&&(this._cachedEmptyGroupNodes=(null==(l=this.nodes)?void 0:l.filter(e=>!!e.children&&0===e.children.length))||[]),e.has("config")&&this.config&&(null==(r=this.config.controls)?void 0:r.multiSelect)!==void 0&&(this.selection=(null==(s=this.config.controls)?void 0:s.multiSelect)?t.MULTI:t.LEAF),super.willUpdate(e)}firstUpdated(e){this.rules||this._loadRulesets(this.global).then(e=>{this.rules=e})}_getSingleNodeSlotTemplate(e){var t,l,r;return o`
            <or-icon slot="prefix" icon="${this._getRulesetLangIcon(null==(t=e.ruleset)?void 0:t.lang)}"></or-icon>
            <span>${e.label}</span>
            <or-icon slot="suffix" icon=${O(this._getRulesetStatusIcon(null==(l=e.ruleset)?void 0:l.status))}
                     class=${this._getRulesetStatusColorClass(null==(r=e.ruleset)?void 0:r.status)}
            ></or-icon>
        `}_getGroupNodeSlotTemplate(e){var t;let l,r=null==(t=e.children)?void 0:t.map(e=>{var t;return null==(t=e.ruleset)?void 0:t.status}).filter(e=>e);if(null==r?void 0:r.find(e=>["LOOP_ERROR","EXECUTION_ERROR","COMPILATION_ERROR"].includes(e))){let e=["LOOP_ERROR","EXECUTION_ERROR","COMPILATION_ERROR"].map(e=>[e,r.filter(t=>t===e).length]).reduce((e,t)=>t[1]>e[1]?t:e)[0];l=this._getRulesetStatusIcon(e)}return o`
            <or-icon slot="prefix" icon="folder"></or-icon>
            <span>${e.label}</span>
            <or-icon slot="suffix" icon=${O(l)} class="iconfill-red"></or-icon>
        `}_getHeaderTemplate(){return o`
            ${y(n.isSuperUser(),()=>o`
                <div id="rules-tree-global-header">
                    <or-translate value="realmRules"></or-translate>
                    <or-mwc-input type=${c.SWITCH} @or-mwc-input-changed=${this._onGlobalSwitch}></or-mwc-input>
                    <or-translate value="globalRules"></or-translate>
                </div>
            `)}
            <div id="tree-header">
                <h3 id="tree-header-title">
                    <or-translate value=${this.menuTitle}></or-translate>
                </h3>
                <div id="tree-header-actions">
                    ${y(1===this._selectedTypes.size&&this._selectedTypes.has("ruleset")&&!this.readonly,()=>o`
                        ${y(1===this._findSelectedTreeNodes().length&&!this._isSelectedLegacyJavascriptRuleset(),()=>o`
                            <or-mwc-input type=${c.BUTTON} icon="content-copy" @or-mwc-input-changed=${this._onCopyClicked}></or-mwc-input>
                        `)}
                        <or-mwc-input type=${c.BUTTON} icon="delete" @or-mwc-input-changed=${this._onDeleteClicked}></or-mwc-input>
                    `)}
                    ${y(1===this._selectedTypes.size&&this._selectedTypes.has("group")&&!this.readonly,()=>o`
                        <or-mwc-input type=${c.BUTTON} icon="delete" @or-mwc-input-changed=${this._onDeleteClicked}></or-mwc-input>
                    `)}
                    ${this._getAddActionTemplate()}
                    ${this._getSortActionTemplate(this.sortBy,this.sortOptions)}
                </div>
            </div>
        `}_onGlobalSwitch(e){this.global=e.detail.value,this.refresh()}_onCopyClicked(e){let t=this._findSelectedTreeNodes();if(1!==t.length)return;let l=t[0];if(this._isLegacyJavascriptRuleset(l.ruleset))return;let r=JSON.parse(JSON.stringify(l.ruleset));delete r.lastModified,delete r.createdOn,delete r.status,delete r.error,delete r.id,r.name=r.name+" copy",(!this.config||!this.config.rulesetCopyHandler||this.config.rulesetCopyHandler(r))&&a.dispatchCancellableEvent(this,new R({ruleset:r,sourceRuleset:l.ruleset})).then(e=>{e.allow&&this.dispatchEvent(new g(e.detail))})}_onDeleteClicked(e){let t=this._findSelectedTreeNodes();if(t.length>0){let e=t.map(e=>e.ruleset).filter(e=>e),l=t.filter(e=>e.children),r=l.map(e=>e.label),s=l.flatMap(e=>e.children).flatMap(e=>e.ruleset?[e.ruleset]:[]);e.push(...s);let i=e.map(e=>({ruleset:e,selected:!0}));if(0===i.length&&l.length>0)return void p(u.t("deleteRulesetGroups"),u.t("deleteRulesetGroupsConfirm",{groupNames:r}),u.t("delete")).then(e=>{e&&(this.deselectAllNodes(),this.nodes=this.nodes.filter(e=>!r.includes(e.label)))});a.dispatchCancellableEvent(this,new m(i)).then(t=>{if(t.allow){let t=e.map(e=>e.name);p(u.t("deleteRulesets"),u.t("deleteRulesetsConfirm",{ruleNames:t}),u.t("delete")).then(t=>{t&&(this.deselectAllNodes(),this._deleteRulesets(e).catch(e=>console.error(e)).finally(()=>{this.nodes=this.nodes.filter(e=>!r.includes(e.label)),this.refresh()}))})}})}}_deleteRulesets(e){return __awaiter(this,void 0,void 0,function*(){let t=[];return e.forEach(e=>{switch(e.type){case"asset":t.push(n.rest.api.RulesResource.deleteAssetRuleset(e.id));break;case"realm":t.push(n.rest.api.RulesResource.deleteRealmRuleset(e.id));break;case"global":t.push(n.rest.api.RulesResource.deleteGlobalRuleset(e.id))}}),Promise.all(t)})}selectRuleset(e,t=!1){let l=this.nodes.find(t=>t.ruleset===e);if(l){let e=this._getUiNodeFromTree(l);e&&this._selectNode(e,!t)}else console.warn("Could not select ruleset; it was not found.")}_dispatchSelectEvent(e){let t=this._lastSelectedNode?this._getTreeNodeFromTree(this._lastSelectedNode):void 0,l=!e||e.length>1?void 0:e[0],r=e=>!!(null==e?void 0:e.children),s=t?r(t)?[{type:"group",groupId:t.id}]:[{type:"rule",ruleset:t.ruleset,selected:!1}]:[],i=l?r(l)?[{type:"group",groupId:l.id}]:[{type:"rule",ruleset:l.ruleset,selected:!0}]:[];if(!this.dispatchEvent(new _({oldNodes:s,newNodes:i})))return!1;this.dispatchEvent(new v({oldNodes:s,newNodes:i}));let o=new Set;return(null==e?void 0:e.find(e=>r(e)))&&o.add("group"),(null==e?void 0:e.find(e=>!r(e)))&&o.add("ruleset"),this._selectedTypes=o,super._dispatchSelectEvent(e)}deselectAllNodes(){super.deselectAllNodes(),this._selectedTypes=new Set}_getRuleNodes(e){let t=Array.from(new Set(e.map(e=>{var t;return null==(t=e.meta)?void 0:t.groupId}).filter(e=>e))).map(t=>({id:t,label:t,children:e.filter(e=>{var l;return(null==(l=e.meta)?void 0:l.groupId)===t}).map(e=>{var t;return{id:null==(t=e.id)?void 0:t.toString(),ruleset:e,label:e.name}})}));return[...e.filter(e=>{var t;return!(null==(t=e.meta)?void 0:t.groupId)}).map(e=>{var t;return{id:null==(t=e.id)?void 0:t.toString(),ruleset:e,label:e.name}}),...t]}_loadRulesets(){return __awaiter(this,arguments,void 0,function*(e=!1,t=n.displayRealm){if(e){let e=n.rest.api.RulesResource.getGlobalRulesets({fullyPopulate:!0});return(yield e).data}{let e=n.rest.api.RulesResource.getRealmRulesets(t,{fullyPopulate:!0});return(yield e).data}})}refresh(){return __awaiter(this,void 0,void 0,function*(){this._cachedEmptyGroupNodes=this.nodes.filter(e=>!!e.children&&0===e.children.length),yield this.getUpdateComplete();let e=this._loadRulesets(this.global);return e.then(e=>{this.rules=e}),e})}_getAddActionTemplate(){let e=(this._getAllowedLanguages()||[]).map(e=>({value:e,text:u.t("rulesLanguages."+e)}));e.push(null),e.push({value:"group",text:u.t("group")});let t=e=>{"group"===e?this._onGroupAddClick():this._onRulesetAddClick(e)};return d(o`
                <or-mwc-input type=${c.BUTTON} icon="plus" title="${u.t("addRule")}"></or-mwc-input>`,e,void 0,e=>t(String(e)))}_onRulesetAddClick(e,t=this.global){if("JAVASCRIPT"===e)return;let l=t?"global":"realm",r=n.isSuperUser()?n.displayRealm:n.config.realm,s={type:l,name:h.DEFAULT_RULESET_NAME,lang:e,realm:r,rules:void 0},i=this._findSelectedTreeNodes();if(1===i.length&&i[0].children){let e=i[0].id;e&&(s.meta=Object.assign(Object.assign({},s.meta||{}),{groupId:e}))}(!this.config||!this.config.rulesetAddHandler||this.config.rulesetAddHandler(s))&&(this.config&&this.config.rulesetTemplates&&this.config.rulesetTemplates[e]?s.rules=this.config.rulesetTemplates[e]:s.rules=T[e].viewRulesetTemplate,"realm"===l&&(s.realm=r),a.dispatchCancellableEvent(this,new R({ruleset:s,isCopy:!1})).then(e=>{e.allow&&this.dispatchEvent(new g(e.detail))}))}_onGroupAddClick(){this.deselectAllNodes();let e=u.t("ruleGroupNameDefault")||"Group name";this.dispatchEvent(new f(e))}_getSortFunction(e){switch(e){case RuleTreeSorting.LANGUAGE:return a.sortByString(e=>{var t;return(null==(t=e.ruleset)?void 0:t.lang)||e.label});case RuleTreeSorting.CREATED_ON:return a.sortByNumber(e=>{var t;return(null==(t=e.ruleset)?void 0:t.createdOn)||0});case RuleTreeSorting.STATUS:return a.sortByString(e=>{var t;return(null==(t=e.ruleset)?void 0:t.status)||e.label});default:return super._getSortFunction(e)}}_getAllowedLanguages(e=this.config,t=this.global){var l;let r=((null==(l=null==e?void 0:e.controls)?void 0:l.allowedLanguages)?[...e.controls.allowedLanguages]:[...OrRuleTree_1.DEFAULT_ALLOWED_LANGUAGES]).filter(e=>"JAVASCRIPT"!==e),s=r.indexOf("GROOVY"),i=r.indexOf("FLOW");return n.isSuperUser()?s<0&&r.push("GROOVY"):s>0&&r.splice(s,1),t&&i>0&&r.splice(i,1),r}_isLegacyJavascriptRuleset(e){return(null==e?void 0:e.lang)==="JAVASCRIPT"}_isSelectedLegacyJavascriptRuleset(){let e=this._findSelectedTreeNodes();return 1===e.length&&this._isLegacyJavascriptRuleset(e[0].ruleset)}_getRulesetLangIcon(e){switch(e){case"JSON":return"ray-start-arrow";case"FLOW":return"transit-connection-variant";case"GROOVY":return"alpha-g-box-outline";case"JAVASCRIPT":return"language-javascript";default:return"mdi-state-machine"}}_getRulesetStatusIcon(e){switch(e){case"DEPLOYED":return;case"READY":return"check";case"COMPILATION_ERROR":case"LOOP_ERROR":case"EXECUTION_ERROR":return"alert-octagon";case"DISABLED":return"minus-circle";case"PAUSED":return"calendar-arrow-right";case"EXPIRED":return"calendar-remove";case"REMOVED":return"close";default:return"stop"}}_getRulesetStatusColorClass(e){switch(e){case"DEPLOYED":case"READY":case"DISABLED":case"PAUSED":case"EXPIRED":case"REMOVED":default:return"iconfill-gray";case"COMPILATION_ERROR":case"LOOP_ERROR":case"EXECUTION_ERROR":return"iconfill-red"}}};OrRuleTree.DEFAULT_ALLOWED_LANGUAGES=["JSON","GROOVY","FLOW"],__decorate([r({type:Array})],OrRuleTree.prototype,"rules",void 0),__decorate([r({type:Object})],OrRuleTree.prototype,"config",void 0),__decorate([r({type:Boolean})],OrRuleTree.prototype,"global",void 0),__decorate([r({type:Boolean})],OrRuleTree.prototype,"readonly",void 0),__decorate([s()],OrRuleTree.prototype,"_loadingPromises",void 0),__decorate([s()],OrRuleTree.prototype,"_selectedTypes",void 0),OrRuleTree=OrRuleTree_1=__decorate([l("or-rule-tree")],OrRuleTree);export{OrRuleTree};