var __decorate=this&&this.__decorate||function(e,t,r,s){var i,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,r):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(n<3?i(o):n>3?i(t,r,o):i(t,r))||o);return n>3&&o&&Object.defineProperty(t,r,o),o},__awaiter=this&&this.__awaiter||function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(o,a)}l((s=s.apply(e,t||[])).next())})};import{css as e,html as t,LitElement as r}from"lit";import{customElement as s,property as i}from"lit/decorators.js";import{getAssetInfos as n,getAssetsByType as o,getAssetTypeFromQuery as a,OrRulesRuleChangedEvent as l,OrRulesRuleUnsupportedEvent as u}from"../index";import{Util as d}from"@openremote/core";import"./or-rule-when";import"./or-rule-then-otherwise";import"@openremote/or-components/or-panel";import{i18next as h,translate as c}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 r of e.items){let e=a(r.assets);e&&t.push([e,r.tag])}if(e.groups)for(let r of e.groups)t=t.concat(getTypeAndTagsFromGroup(r));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 c(h)(r){static get styles(){return style}constructor(){super(),this._unsupported=!1,this._activeAssetPromises=new Map,this.addEventListener(OrRulesJsonRuleChangedEvent.NAME,this._onJsonRuleChanged)}connectedCallback(){super.connectedCallback(),this._unsupported&&this.dispatchEvent(new u)}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 u):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 u):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,t)=>this.loadAssets(e,t)}"
                ></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,t)=>this.loadAssets(e,t)}"
                ></or-rule-then-otherwise>
            </div>
        `}loadAssets(e,t){return __awaiter(this,void 0,void 0,function*(){if(this._activeAssetPromises.has(e))return(yield this._activeAssetPromises.get(e)).assets;{null!=t||(t={}),null!=t.types||(t.types=[]),t.types.push(e),null!=t.realm||(t.realm={name:"realm"==this._ruleset.type?this._ruleset.realm:void 0});let r=o(e,t);this._activeAssetPromises.set(e,r);let s=yield r;return this._activeAssetPromises.delete(e),s.assets}})}loadAssetDescriptors(e){n(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&&!d.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 r;if(!t)return!0;for(let s of t)switch(s.action){case"wait":if(!s.millis)return!1;break;case"write-attribute":if(!s.attributeName||!this._validateAssetTarget(e,s.target))return!1;break;case"notification":case"alarm":break;case"webhook":if(!(null==(r=s.webhook)?void 0:r.url)||!s.webhook.httpMethod)return!1;break;case"update-attribute":if(!s.attributeName||!s.updateAction||!this._validateAssetTarget(e,s.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,r){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(!r&&(!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"geojson":return void 0!==e.geoJSON&&this._validateGeoJSON(JSON.parse(e.geoJSON));case"array":return e.index&&!e.value||e.value||e.lengthEquals||e.lengthLessThan||e.lengthGreaterThan;case"value-empty":return!0;default:return!1}}_validateGeoJSON(e){if(!e)return!1;let t=["Polygon","MultiPolygon"],r=e=>!!e&&!!e.type&&(!!t.includes(e.type)||"GeometryCollection"===e.type&&!!Array.isArray(e.geometries)&&e.geometries.every(e=>r(e)));return"FeatureCollection"===e.type?!!Array.isArray(e.features)&&e.features.every(e=>r(e.geometry)):"Feature"===e.type?r(e.geometry):r(e)}};__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),OrRuleJsonViewer=__decorate([s("or-rule-json-viewer")],OrRuleJsonViewer);export{OrRuleJsonViewer};