var OrRuleActionNotification_1,__decorate=this&&this.__decorate||function(t,e,i,o){var a,n=arguments.length,s=n<3?e:null===o?o=Object.getOwnPropertyDescriptor(e,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,i,o);else for(var r=t.length-1;r>=0;r--)(a=t[r])&&(s=(n<3?a(s):n>3?a(e,i,s):a(e,i))||s);return n>3&&s&&Object.defineProperty(e,i,s),s},__awaiter=this&&this.__awaiter||function(t,e,i,o){return new(i||(i=Promise))(function(a,n){function s(t){try{l(o.next(t))}catch(t){n(t)}}function r(t){try{l(o.throw(t))}catch(t){n(t)}}function l(t){var e;t.done?a(t.value):((e=t.value)instanceof i?e:new i(function(t){t(e)})).then(s,r)}l((o=o.apply(t,e||[])).next())})};import{css as t,html as e,LitElement as i}from"lit";import{customElement as o,property as a}from"lit/decorators.js";import{until as n}from"lit/directives/until.js";import{OrRulesRuleUnsupportedEvent as s}from"../index";import{InputType as r}from"@openremote/or-mwc-components/or-mwc-input";import{getTargetTypeMap as l,OrRulesJsonRuleChangedEvent as c}from"./or-rule-json-viewer";import"./modals/or-rule-notification-modal";import"./forms/or-rule-form-email-message";import"./forms/or-rule-form-push-notification";import"./forms/or-rule-form-localized";import"./or-rule-action-attribute";import{i18next as u}from"@openremote/or-translate";import d,{Util as g}from"@openremote/core";let style=t`
    :host {
        display: flex;
        align-items: center;
    }

    :host > * {
        margin: 0 3px 6px;
    }

    .min-width {
        min-width: 200px;
    }
`,OrRuleActionNotification=OrRuleActionNotification_1=class extends i{static get styles(){return style}connectedCallback(){return this.addEventListener(c.NAME,this._onJsonRuleChanged),this._initialAction=structuredClone(this.action),super.connectedCallback()}willUpdate(t){return t.has("rule")&&void 0!==t.get("rule")&&(this._initialAction=structuredClone(this.action)),super.willUpdate(t)}disconnectedCallback(){return this.removeEventListener(c.NAME,this._onJsonRuleChanged),super.disconnectedCallback()}_onJsonRuleChanged(){var t,e,i,o,a,n,s;if(this.action.notification){let r=this.action.notification.message;if((null==r?void 0:r.type)==="localized"){let l=(null==(i=null==(e=null==(t=this.config)?void 0:t.notifications)?void 0:e[d.displayRealm])?void 0:i.defaultLanguage)||(null==(n=null==(a=null==(o=this.config)?void 0:o.notifications)?void 0:a.default)?void 0:n.defaultLanguage)||d.config.defaultLanguage,c=null==(s=r.languages)?void 0:s[l];(null==c?void 0:c.type)==="push"?this.action.notification.name=c.title:(null==c?void 0:c.type)==="email"&&(this.action.notification.name=c.subject)}else(null==r?void 0:r.type)==="push"?this.action.notification.name=r.title:(null==r?void 0:r.type)==="email"&&(this.action.notification.name=r.subject)}}static getActionTargetTemplate(t,i,o,a,n,s,l,c){let m,p=[["USER",u.t("user_plural")],["ASSET",u.t("asset_plural")],["REALM",u.t("realm_plural")],["CUSTOM",u.t("custom")]];if(n&&n.controls&&n.controls.allowedActionTargetTypes){let t;(t=n.controls.allowedActionTargetTypes.actions?n.controls.allowedActionTargetTypes.actions[o]:n.controls.allowedActionTargetTypes.default)&&(p=p.filter(e=>null==t?void 0:t.includes(e[0])))}if(0===p.length)return void console.warn("Rule action config doesn't allow any action target types for this type of action");let f="ASSET";if(i.target&&(!i.target.users||i.target.conditionAssets||i.target.matchedAssets||i.target.assets?i.target.linkedUsers?f="USER":void 0===i.target.custom||i.target.conditionAssets||i.target.matchedAssets||i.target.assets||(f="CUSTOM"):f="USER"),p.find(t=>t[0]===f)||(f=void 0),"CUSTOM"===f)m=Promise.resolve(e`
                <or-mwc-input class="min-width" .type="${r.TEXT}" @or-mwc-input-changed="${t=>c(f,t.detail.value)}" ?readonly="${a}" .value="${i.target.custom}" ></or-mwc-input>            
            `);else{let o,n,l;if("USER"===f){let t={realmPredicate:{name:d.displayRealm},select:{basic:!0},serviceUsers:!1,attributes:[{name:{value:"systemAccount",predicateType:"string"},negated:!0}]};o=d.rest.api.UserResource.query(t).then(t=>__awaiter(this,void 0,void 0,function*(){let e=u.t("linked"),i=(yield d.rest.api.RealmResource.get(d.displayRealm)).data.realmRoles.map(t=>["linked-"+t.name,e+": "+u.t("realmRole."+t.name,g.camelCaseToSentenceCase(t.name.replace("_"," ").replace("-"," ")))]);return[["linkedUsers",e],...i,...t.data.map(t=>[t.id,t.username]).sort(g.sortByString(t=>t[1]))]})),n=u.t("user_plural");let e=i.target.users;if(i.target.linkedUsers)if(e&&e.realmRoles){if(e.realmRoles.length>1)return void console.warn("Rule action user target query is unsupported: "+JSON.stringify(e,null,2));l="linked-"+e.realmRoles[0].value}else l="linkedUsers";else{if(!e||e.ids&&e.ids.length>1||e.usernames||e.assets||e.limit||e.pathPredicate||e.realmPredicate)return void console.warn("Rule action user target query is unsupported: "+JSON.stringify(e,null,2));e.ids&&1===e.ids.length&&(l=e.ids[0])}}else{let e=s?Object.assign({},s):{};if(e.orderBy={property:"NAME"},o=d.rest.api.AssetResource.queryAssets(e).then(e=>{let i=e.data.map(t=>[t.id,t.name+" ("+t.id+")"]),o=[["allMatched",u.t("matched")]];return t&&t.length>1&&t.forEach(t=>{o.find(e=>e[0]===t[0])||o.push([t[0],u.t("matchedOfType",{type:g.getAssetTypeLabel(t[0])})])}),[...o,...i]}),n=u.t("asset_plural"),i.target){if(i.target.conditionAssets)return void console.warn("Rule action asset target, conditionAssets is unsupported: "+JSON.stringify(i.target,null,2));if(i.target.matchedAssets){if(i.target.matchedAssets.types&&i.target.matchedAssets.types.length>1)return void console.warn("Rule action asset target, matchedAssets query unsupported: "+JSON.stringify(i.target,null,2));i.target.matchedAssets.types&&1===i.target.matchedAssets.types.length&&(l=i.target.matchedAssets.types[0])}else if(i.target.assets){if(i.target.assets.ids&&i.target.assets.ids.length>1)return void console.warn("Rule action asset target, assets query unsupported: "+JSON.stringify(i.target,null,2));i.target.assets.ids&&1===i.target.assets.ids.length&&(l=i.target.assets.ids[0])}}else l="allMatched"}m=o.then(t=>e`
                    <or-mwc-input type="${r.SELECT}" 
                        class="min-width"
                        .options="${t}"
                        .label="${n}"
                        .value="${l}"
                        @or-mwc-input-changed="${t=>c(f,t.detail.value)}" 
                        ?readonly="${a}"></or-mwc-input>
                `)}return m.then(t=>e`
                <or-mwc-input type="${r.SELECT}" 
                    class="min-width"
                    .options="${p}"
                    .value="${f}"
                    .label="${u.t("recipients")}"
                    @or-mwc-input-changed="${t=>l(t.detail.value)}" 
                    ?readonly="${a}"></or-mwc-input>
                ${t}
            `)}render(){var t,i,o,a;let r;if(!this.action.notification||!this.action.notification.message)return e``;let u=this.action.notification.message,g=u.type;r="push"===g?{types:["ConsoleAsset"]}:{attributes:{items:[{name:{predicateType:"string",value:"email"},value:{predicateType:"value-empty",negate:!0}}]}};let m=OrRuleActionNotification_1.getActionTargetTemplate(l(this.rule),this.action,this.actionType,!!this.readonly,this.config,r,t=>this._onTargetTypeChanged(t),(t,e)=>this._onTargetChanged(t,e)),p="";if(!m)return this.dispatchEvent(new s),"";let f=t=>{var e,i;if(this._initialAction&&this.action.notification){let t=structuredClone(this._initialAction);JSON.stringify(this.action.notification.message)!==JSON.stringify(null==(e=t.notification)?void 0:e.message)?(console.debug("Rolling back the notification to former state..."),this.action.notification.message=null==(i=t.notification)?void 0:i.message,this.requestUpdate("action")):console.debug("Rolling back was not necessary, as no changes have been done.")}else console.warn("Could not rollback notification form.")},h=t=>{this._initialAction=structuredClone(this.action),this.dispatchEvent(new c)};if(u){if("push"===g)p=e`
                    <or-rule-notification-modal title="push-notification" .action="${this.action}"
                                                @or-rules-notification-modal-cancel="${f}"
                                                @or-rules-notification-modal-ok="${h}">
                        <or-rule-form-push-notification .message="${u}"></or-rule-form-push-notification>
                    </or-rule-notification-modal>
                `;else if("email"===g)p=e`
                    <or-rule-notification-modal title="email" .action="${this.action}"
                                                @or-rules-notification-modal-cancel="${f}"
                                                @or-rules-notification-modal-ok="${h}">
                        <or-rule-form-email-message .message="${u}"></or-rule-form-email-message>
                    </or-rule-notification-modal>
                `;else if("localized"===g){let n=(null==(i=null==(t=this.config)?void 0:t.notifications)?void 0:i[d.displayRealm])||(null==(a=null==(o=this.config)?void 0:o.notifications)?void 0:a.default),s=[...new Set([...(null==n?void 0:n.languages)||[],...Object.keys(u.languages||{})||[]])],r=(null==n?void 0:n.defaultLanguage)||d.config.defaultLanguage;0===s.length&&r&&s.push(r);let l=r!==u.defaultLanguage,c="email_localized"===this.actionType?"email":"push",g="email_localized"===this.actionType?"email":"push-notification";p=e`
                    <or-rule-notification-modal title="${g}" .action="${this.action}"
                                                @or-rules-notification-modal-cancel="${f}"
                                                @or-rules-notification-modal-ok="${h}">
                        <or-rule-form-localized .message="${u}" .type="${c}" .languages="${s}" .defaultLang="${r}" 
                                                .wrongLanguage="${l}"
                        ></or-rule-form-localized>
                    </or-rule-notification-modal>
                `}}return m=m.then(t=>e`
                ${t}
                ${p}
            `),e`${n(m,e``)}`}_onTargetTypeChanged(t){"ASSET"===t?delete this.action.target:"USER"===t?this.action.target={users:{ids:[]}}:"CUSTOM"===t&&(this.action.target={custom:""}),this.dispatchEvent(new c),this.requestUpdate()}_onTargetChanged(t,e){switch(t){case"USER":"linkedUsers"===e?this.action.target={linkedUsers:!0}:(null==e?void 0:e.startsWith("linked-"))?this.action.target={users:{realmRoles:[{predicateType:"string",value:null==e?void 0:e.substring(7)}]},linkedUsers:!0}:e&&(this.action.target={users:{ids:[e]}});break;case"CUSTOM":this.action.target={custom:e};break;case"ASSET":e&&"allMatched"!==e?e.endsWith("Asset")?this.action.target={matchedAssets:{types:[e]}}:this.action.target={assets:{ids:[e]}}:delete this.action.target}this.dispatchEvent(new c)}};__decorate([a({type:Object,attribute:!1})],OrRuleActionNotification.prototype,"rule",void 0),__decorate([a({type:Object,attribute:!1})],OrRuleActionNotification.prototype,"action",void 0),__decorate([a({type:String,attribute:!1})],OrRuleActionNotification.prototype,"actionType",void 0),__decorate([a({type:Object})],OrRuleActionNotification.prototype,"assetInfos",void 0),__decorate([a({type:Object})],OrRuleActionNotification.prototype,"config",void 0),OrRuleActionNotification=OrRuleActionNotification_1=__decorate([o("or-rule-action-notification")],OrRuleActionNotification);export{OrRuleActionNotification};