var __decorate=this&&this.__decorate||function(e,t,s,r){var i,n=arguments.length,o=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,s):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,s,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,s,o):i(t,s))||o);return n>3&&o&&Object.defineProperty(t,s,o),o},__awaiter=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{u(r.next(e))}catch(e){n(e)}}function a(e){try{u(r.throw(e))}catch(e){n(e)}}function u(e){var t;e.done?i(e.value):((t=e.value)instanceof s?t:new s(function(e){e(t)})).then(o,a)}u((r=r.apply(e,t||[])).next())})};import{css as e,html as t,LitElement as s}from"lit";import{customElement as r,property as i,state as n}from"lit/decorators.js";import{getAssetInfos as o,getAssetsByType as a,getAssetTypeFromQuery as u,OrRulesRuleChangedEvent as l,OrRulesRuleUnsupportedEvent as d}from"../index";import{Util as h}from"@openremote/core";import"./or-rule-when";import"./or-rule-then-otherwise";import"@openremote/or-components/or-panel";import{i18next as c,translate as p}from"@openremote/or-translate";export class OrRulesJsonRuleChangedEvent extends CustomEvent{constructor(){super(OrRulesJsonRuleChangedEvent.NAME,{bubbles:!0,composed:!0})}}function getTypeAndTagsFromGroup(e){if(!e)return[];let t=[];if(e.items)for(let s of e.items){let e=u(s.assets);e&&t.push([e,s.tag])}if(e.groups)for(let s of e.groups)t=t.concat(getTypeAndTagsFromGroup(s));return t}OrRulesJsonRuleChangedEvent.NAME="or-rules-json-rule-changed";export function getTargetTypeMap(e){return e.when?getTypeAndTagsFromGroup(e.when):[]}let style=e`
    :host {
        display: flex;
        width: calc(100% - 20px);
        padding: 0px 10px;
        margin-top: -10px;
    }
    
    :host > * {
        flex: 1;
    }

    @media screen and (max-width: 1400px) {
        :host > * {
            flex-grow: 0;
        }

        :host {
            flex-direction: column;
        }
    }
`,OrRuleJsonViewer=class extends p(c)(s){static get styles(){return style}constructor(){super(),this._loadedAssets=new Map,this._unsupported=!1,this._activeAssetPromises=new Map,this.addEventListener(OrRulesJsonRuleChangedEvent.NAME,this._onJsonRuleChanged)}connectedCallback(){super.connectedCallback(),this._unsupported&&this.dispatchEvent(new d)}disconnectedCallback(){return this.removeEventListener(OrRulesJsonRuleChangedEvent.NAME,this._onJsonRuleChanged),super.disconnectedCallback()}set ruleset(e){if(this._ruleset!==e)if(this._unsupported=!1,this._ruleset=e,e.rules)try{let t=JSON.parse(e.rules);if(!t.rules||t.rules.length>1)return void(this.isConnected?this.dispatchEvent(new d):this._unsupported=!0);this._rule=t.rules[0],this.requestUpdate()}catch(e){console.error("Invalid JSON rules, failed to parse: "+e),this.isConnected?this.dispatchEvent(new d):this._unsupported=!0}else this.config&&this.config.json&&this.config.json.rule?this._rule=JSON.parse(JSON.stringify(this.config.json.rule)):this._rule={recurrence:{mins:0}}}updated(e){e.has("config")&&(this.loadAssetDescriptors(!1),this.loadAssetDescriptors(!0))}render(){if(!this._rule)return t``;let e=getTargetTypeMap(this._rule);return t`
            <div class="section-container">                                    
                <or-rule-when .rule="${this._rule}" .config="${this.config}" .assetInfos="${this._whenAssetInfos}" ?readonly="${this.readonly}" 
                              .assetProvider="${e=>__awaiter(this,void 0,void 0,function*(){return this.loadAssets(e)})}"
                ></or-rule-when>
            </div>
        
            <div class="section-container">              
                <or-rule-then-otherwise .rule="${this._rule}" .config="${this.config}" .targetTypeMap="${e}" .assetInfos="${this._actionAssetInfos}" ?readonly="${this.readonly}" 
                                        .assetProvider="${e=>__awaiter(this,void 0,void 0,function*(){return this.loadAssets(e)})}"
                ></or-rule-then-otherwise>
            </div>
        `}loadAssets(e){return __awaiter(this,void 0,void 0,function*(){if(this._activeAssetPromises.has(e))return(yield this._activeAssetPromises.get(e)).assets;{let t=a(e,"realm"==this._ruleset.type?this._ruleset.realm:void 0,this._loadedAssets);this._activeAssetPromises.set(e,t);let s=yield t;return this._activeAssetPromises.delete(e),s.assets}})}loadAssetDescriptors(e){o(this.config,e).then(t=>{e?this._actionAssetInfos=[...t]:this._whenAssetInfos=[...t],this.requestUpdate()})}beforeSave(){if(!this._rule)return;this._rule.name=this._ruleset.name;let e={rules:[this._rule]};this._ruleset.rules=JSON.stringify(e)}validate(){let e=this._rule;return!!e&&!!e.when&&!!e.then&&0!==e.then.length&&!!this._validateConditionGroup(e.when)&&!!this._validateRuleActions(e,e.then)}_onJsonRuleChanged(){let e=this.validate();this.dispatchEvent(new l(e))}_validateConditionGroup(e){if((!e.items||0===e.items.length)&&(!e.groups||0===e.groups.length))return!1;if(e.items){for(let t of e.items)if(!t.assets&&!t.cron&&!t.sun||t.cron&&!h.cronStringToISOString(t.cron,!0)||t.sun&&(!t.sun.position||!t.sun.location)||t.assets&&!this._validateAssetQuery(t.assets,!0,!1))return!1}if(e.groups){for(let t of e.groups)if(!this._validateConditionGroup(t))return!1}return!0}_validateRuleActions(e,t){var s;if(!t)return!0;for(let r of t)switch(r.action){case"wait":if(!r.millis)return!1;break;case"write-attribute":if(!r.attributeName||!this._validateAssetTarget(e,r.target))return!1;break;case"notification":case"alarm":break;case"webhook":if(!(null==(s=r.webhook)?void 0:s.url)||!r.webhook.httpMethod)return!1;break;case"update-attribute":if(!r.attributeName||!r.updateAction||!this._validateAssetTarget(e,r.target))return!1;break;default:return!1}return!0}_validateAssetTarget(e,t){return!t||(t.assets?this._validateAssetQuery(t.assets,!1,!1):t.matchedAssets?this._validateAssetQuery(t.matchedAssets,!1,!0):!(t.conditionAssets&&0>getTypeAndTagsFromGroup(e.when).findIndex(e=>t.conditionAssets===e[1])))}_validateAssetQuery(e,t,s){if(!e.types||0===e.types.length)return!1;if(t){if(!e.attributes||!e.attributes.items||0===e.attributes.items.length)return!1}else if(!s&&(!e.ids||0===e.ids.length))return!1;if(e.attributes&&e.attributes.items){for(let t of e.attributes.items)if(!t.name||!t.name.match||!t.name.value||!t.timestampOlderThan&&(!t.value||!this._validateValuePredicate(t.value)))return!1}return!0}_validateValuePredicate(e){switch(e.predicateType){case"string":return void 0!==e.match&&void 0!==e.value;case"boolean":return void 0!==e.value;case"datetime":case"number":return void 0!==e.operator&&void 0!==e.value&&("BETWEEN"!==e.operator||void 0!==e.rangeValue);case"radial":return void 0!==e.radius&&void 0!==e.lat&&void 0!==e.lng;case"rect":return void 0!==e.lngMax&&void 0!==e.latMax&&void 0!==e.lngMin&&void 0!==e.latMin;case"array":return e.index&&!e.value||e.value||e.lengthEquals||e.lengthLessThan||e.lengthGreaterThan;case"value-empty":return!0;default:return!1}}};__decorate([i({attribute:!1})],OrRuleJsonViewer.prototype,"readonly",void 0),__decorate([i({attribute:!1})],OrRuleJsonViewer.prototype,"config",void 0),__decorate([i({attribute:!1})],OrRuleJsonViewer.prototype,"_ruleset",void 0),__decorate([n()],OrRuleJsonViewer.prototype,"_loadedAssets",void 0),OrRuleJsonViewer=__decorate([r("or-rule-json-viewer")],OrRuleJsonViewer);export{OrRuleJsonViewer};