var __decorate=this&&this.__decorate||function(t,e,r,i){var a,s=arguments.length,n=s<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,r,i);else for(var o=t.length-1;o>=0;o--)(a=t[o])&&(n=(s<3?a(n):s>3?a(e,r,n):a(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n},__awaiter=this&&this.__awaiter||function(t,e,r,i){return new(r||(r=Promise))(function(a,s){function n(t){try{u(i.next(t))}catch(t){s(t)}}function o(t){try{u(i.throw(t))}catch(t){s(t)}}function u(t){var e;t.done?a(t.value):((e=t.value)instanceof r?e:new r(function(t){t(e)})).then(n,o)}u((i=i.apply(t,e||[])).next())})};import{css as t,html as e,LitElement as r}from"lit";import{customElement as i,property as a,state as s}from"lit/decorators.js";import{AssetModelUtil as n}from"@openremote/model";import{AssetQueryOperator as o,getAssetIdsFromQuery as u,getAssetTypeFromQuery as l}from"../index";import"@openremote/or-mwc-components/or-mwc-input";import{InputType as d}from"@openremote/or-mwc-components/or-mwc-input";import"@openremote/or-attribute-input";import{Util as p}from"@openremote/core";import{i18next as c,translate as T}from"@openremote/or-translate";import{buttonStyle as E}from"../style";import{OrRulesJsonRuleChangedEvent as h}from"./or-rule-json-viewer";import"./modals/or-rule-radial-modal";import{ifDefined as _}from"lit/directives/if-defined.js";import{when as m}from"lit/directives/when.js";import N from"moment";let style=t`
    
    ${E}
    
    :host {
        display: block;
    }
    
    .attribute-group {
        flex-grow: 1;
        display: flex;
        align-items: start;
        flex-direction: row;
        flex-wrap: wrap;
    }

    .min-width {
        min-width: 200px;
    }
    
    .attribute-group > * {
        margin: 10px 3px 6px 3px;
    }
    .attributes {
        flex: 1 1 min-content;
        display: flex;
        flex-direction: column;
        row-gap: 10px;
    }
    or-icon.small {
        --or-icon-width: 14px;
        --or-icon-height: 14px;
    }
    .attribute {
        display: flex;
        align-items: center;
    }
    .attribute > div {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        align-items: center;
        gap: 6px;
    }
    .attribute > div > or-rule-radial-modal {
        min-width: auto;
    }
    .attribute > div > or-mwc-input[type="button"] {
        min-width: auto;
    }
    .attribute > div > or-mwc-input:not([type="button"]) {
        width: 200px;
    }
    .attribute > div > or-attribute-input {
        width: 200px;
    }
    .attribute > div > * {
        min-width: 200px;
    }
    .button-clear {
        margin-left: auto;
    }
    .attribute:hover .button-clear {
        visibility: visible;
    }
    
    .invalidLabel {
        display: flex;
        align-items: center;
        margin: 14px 3px auto 0;
        height: 48px; /* Same as the icon size */
    }
`,OrRuleAssetQuery=class extends T(c)(r){constructor(){super(),this._queryOperatorsMap={},this._queryOperatorsMap.GEO_JSONPoint=[o.EQUALS,o.NOT_EQUALS,o.WITHIN_RADIUS,o.OUTSIDE_RADIUS,o.WITHIN_RECTANGLE,o.OUTSIDE_RECTANGLE,o.VALUE_EMPTY,o.VALUE_NOT_EMPTY,o.NOT_UPDATED_FOR],this._queryOperatorsMap.string=[o.EQUALS,o.NOT_EQUALS,o.CONTAINS,o.NOT_CONTAINS,o.STARTS_WITH,o.NOT_STARTS_WITH,o.ENDS_WITH,o.NOT_ENDS_WITH,o.VALUE_EMPTY,o.VALUE_NOT_EMPTY,o.NOT_UPDATED_FOR],this._queryOperatorsMap.number=[o.EQUALS,o.NOT_EQUALS,o.GREATER_THAN,o.GREATER_EQUALS,o.LESS_THAN,o.LESS_EQUALS,o.BETWEEN,o.NOT_BETWEEN,o.VALUE_EMPTY,o.VALUE_NOT_EMPTY,o.NOT_UPDATED_FOR],this._queryOperatorsMap.boolean=[o.IS_TRUE,o.IS_FALSE,o.VALUE_EMPTY,o.VALUE_NOT_EMPTY,o.NOT_UPDATED_FOR],this._queryOperatorsMap.array=[o.CONTAINS,o.NOT_CONTAINS,o.INDEX_CONTAINS,o.NOT_INDEX_CONTAINS,o.LENGTH_EQUALS,o.NOT_LENGTH_EQUALS,o.LENGTH_LESS_THAN,o.LENGTH_GREATER_THAN,o.VALUE_EMPTY,o.VALUE_NOT_EMPTY,o.NOT_UPDATED_FOR],this._queryOperatorsMap.object=[o.CONTAINS_KEY,o.NOT_CONTAINS_KEY,o.VALUE_EMPTY,o.VALUE_NOT_EMPTY,o.NOT_UPDATED_FOR]}refresh(){this._assets=void 0}attributePredicateEditorTemplate(t,r,i){let a=t.assetDescriptor,s=this.getOperator(i),o=this.getAttributeName(i),u=r&&r.attributes&&o?r.attributes[o]:void 0,l=[],T=n.getAttributeAndValueDescriptors(r?r.type:a.name,u||o,u);(l=r&&r.attributes?Object.values(r.attributes).filter(t=>t.meta&&(t.meta.hasOwnProperty("ruleState")?t.meta.ruleState:t.meta.hasOwnProperty("agentLink"))).map(t=>{let e=n.getAttributeAndValueDescriptors(r.type,t.name,t),i=p.getAttributeLabel(t,e[0],r.type,!1);return[t.name,i]}):t&&t.attributeDescriptors?t.attributeDescriptors.map(t=>{let e=n.getAttributeAndValueDescriptors(a.name,t),r=p.getAttributeLabel(void 0,e?e[0]:void 0,a.name,!1);return[t.name,r]}):[]).sort(p.sortByString(t=>t[1]));let E=o?this.getOperators(a,T?T[0]:void 0,T?T[1]:void 0,u,o):[];return e`
            <or-mwc-input type="${d.SELECT}" @or-mwc-input-changed="${t=>this.setAttributeName(i,t.detail.value)}" .readonly="${this.readonly||!1}" .options="${l}" .value="${o}" .label="${c.t("attribute")}"></or-mwc-input>
            ${o?e`<or-mwc-input type="${d.SELECT}" @or-mwc-input-changed="${t=>this.setOperator(a,u,o,i,t.detail.value)}" .readonly="${this.readonly||!1}" .options="${E}" .value="${s}" .label="${c.t("operator")}"></or-mwc-input>`:""}
            ${i?this.attributePredicateValueEditorTemplate(a,r,i):""}
        `}attributePredicateValueEditorTemplate(t,r,i){var a,s,u,p,T,E,m;if(this.getOperator(i)===o.NOT_UPDATED_FOR){let t=i.timestampOlderThan?N.duration(i.timestampOlderThan):void 0;return e`
                <or-mwc-input type="${d.NUMBER}" 
                              min="0"
                              .value="${null==t?void 0:t.asMinutes()}"
                              label="${c.t("rulesEditorDuration")}"
                              @or-mwc-input-changed="${t=>{let e=t.detail.value,r=N.duration(e,"minutes");i.timestampOlderThan=e>0?r.toISOString():void 0,this.dispatchEvent(new h)}}">
                </or-mwc-input>`}let A=i.value;if(!t||!A)return"";let y=this.getAttributeName(i),b=l(this.query),O=r&&r.attributes&&y?r.attributes[y]:void 0,v=n.getAttributeAndValueDescriptors(b,y,O),S=A?A.value:void 0;switch(A.predicateType){case"string":return e`<or-attribute-input @or-attribute-input-changed="${t=>this.setValuePredicateProperty(A,"value",t.detail.value)}" .customProvider="${null==(a=this.config)?void 0:a.inputProvider}" .label="${c.t("value")}" .assetType="${b}" .attributeDescriptor="${v[0]}" .attributeValueDescriptor="${v[1]}" .value="${S}" .readonly="${this.readonly||!1}" .fullWidth="${!0}"></or-attribute-input>`;case"boolean":return e``;case"datetime":case"rect":default:return e`<span>NOT IMPLEMENTED</span>`;case"number":let g;if("BETWEEN"===A.operator)return e`
                        <or-attribute-input .inputType="${d.NUMBER}" @or-attribute-input-changed="${t=>this.setValuePredicateProperty(A,"value",t.detail.value)}" .customProvider="${null==(s=this.config)?void 0:s.inputProvider}" .label="${c.t("between")}" .assetType="${b}" .attributeDescriptor="${v[0]}" .attributeValueDescriptor="${v[1]}" .value="${S}" .readonly="${this.readonly||!1}" .fullWidth="${!0}"></or-attribute-input>
                        <span style="display: inline-flex; align-items: center;">&</span>
                        <or-attribute-input .inputType="${d.NUMBER}" @or-attribute-input-changed="${t=>this.setValuePredicateProperty(A,"rangeValue",t.detail.value)}" .customProvider="${null==(u=this.config)?void 0:u.inputProvider}" .label="${c.t("and")}" .assetType="${b}" .attributeDescriptor="${v[0]}" .attributeValueDescriptor="${v[1]}" .value="${A.rangeValue}" .readonly="${this.readonly||!1}" .fullWidth="${!0}"></or-attribute-input>
                    `;return(null==(T=null==(p=v[0])?void 0:p.format)?void 0:T.asSlider)&&(g=d.NUMBER),e`<or-attribute-input .inputType="${_(g)}" @or-attribute-input-changed="${t=>this.setValuePredicateProperty(A,"value",t.detail.value)}" .customProvider="${null==(E=this.config)?void 0:E.inputProvider}" .label="" .assetType="${b}" .attributeDescriptor="${v[0]}" .attributeValueDescriptor="${v[1]}" .value="${S}" .readonly="${this.readonly||!1}" .fullWidth="${!0}"></or-attribute-input>`;case"radial":return e`<or-rule-radial-modal .query="${this.query}" .assetDescriptor="${t}" .attributePredicate="${i}"></or-rule-radial-modal>`;case"value-empty":return"";case"array":return e`<or-attribute-input @or-attribute-input-changed="${t=>this.setValuePredicateProperty(A,"value",t.detail.value)}" .customProvider="${null==(m=this.config)?void 0:m.inputProvider}" .label="" .assetType="${b}" .attributeDescriptor="${v[0]}" .attributeValueDescriptor="${v[1]}" .value="${S}" .readonly="${this.readonly||!1}" .fullWidth="${!0}></or-attribute-input>`}}attributeDurationTemplate(t,r,i,a){var s,n;let u=null==(n=null==(s=this.query.attributes)?void 0:s.items)?void 0:n[r];if((u?this.getOperator(u):void 0)===o.NOT_UPDATED_FOR)return e``;if(!t.has(r))return e`
                <or-mwc-input type="${d.BUTTON}" .readonly="${this.readonly||!1}" icon="clock-plus-outline"
                              title="${c.t("rulesEditorAddDuration")}" @or-mwc-input-changed="${()=>i(r)}"
                ></or-mwc-input>
            `;{let i=t.get(r),s=i?N.duration(i):void 0;return e`
                <or-mwc-input type="${d.NUMBER}" min="0" .readonly="${this.readonly||!1}"
                              .value="${null==s?void 0:s.asMinutes()}" label="${c.t("rulesEditorDuration")}"
                              @or-mwc-input-changed="${t=>{let e=N.duration(t.detail.value,"minutes");e.asMinutes()>0?a(r,e.toISOString()):a(r,void 0)}}"
                ></or-mwc-input>
            `}}static get styles(){return style}shouldUpdate(t){return t.has("condition")&&(this._assets=void 0),super.shouldUpdate(t)}get query(){return this.condition.assets}get duration(){var t;return(null==(t=this.condition)?void 0:t.duration)?new Map(Object.entries(this.condition.duration).map(([t,e])=>[Number(t),e])):new Map}set duration(t){t.size>0?this.condition.duration=Object.fromEntries(t):this.condition.duration=void 0}render(){let t,r=l(this.query);if(!r)return e`<span class="invalidLabel">${c.t("errorOccurred")}</span>`;let i=this.assetInfos?this.assetInfos.find(t=>t.assetDescriptor.name===r):void 0;if(!i)return e`<span class="invalidLabel">${c.t("errorOccurred")}</span>`;this._assets||this.loadAssets(r),this.query.attributes||(this.query.attributes={}),this.query.attributes.items&&0!==this.query.attributes.items.length||(this.query.attributes.items=[{}]);let a=!this.readonly&&this.query.attributes&&this.query.attributes.items&&this.query.attributes.items.length>1,s=u(this.query),n=s&&s.length>0?s[0]:"*",o=[["*",c.t("anyOfThisType")]];return e`
            <div class="attribute-group">
            
                <!-- Show SELECT input with 'loading' until the assets are retrieved -->
                ${m(!this._assets,()=>e`
                    <or-mwc-input id="idSelect" class="min-width" type="${d.SELECT}" .readonly="${!0}" .label="${c.t("loading")}"></or-mwc-input>
                `,()=>{this._assets.length<=25?o.push(...this._assets.map(t=>[t.id,t.name])):t=t=>__awaiter(this,void 0,void 0,function*(){var e;if(t)return this._assets.filter(e=>{var r;return null==(r=e.name)?void 0:r.toLowerCase().includes(t.toLowerCase())}).map(t=>[t.id,t.name]);if(this._assets.length<=100)return o.push(...this._assets.map(t=>[t.id,t.name])),o;{let t=null==(e=this._assets)?void 0:e.find(t=>t.id==n);return t&&void 0==o.find(([e,r])=>e==t.id)&&o.push([t.id,t.name]),o}});let r=!this.readonly&&(!this.config||!this.config.controls||!0!==this.config.controls.hideWhenAddAttribute),s=t=>{this.duration=this.duration.set(t,void 0),this.requestUpdate()},u=(t,e)=>{console.debug("Updating duration of rule condition to ",e),this.duration=this.duration.set(t,e),this.dispatchEvent(new h),this.requestUpdate()};return e`
                        <or-mwc-input id="idSelect" class="min-width filledSelect" type="${d.SELECT}" .readonly="${this.readonly||!1}" .label="${c.t("asset")}" 
                                      .options="${o}" .value="${n}" .searchProvider="${t}"
                                      @or-mwc-input-changed="${t=>{this._assetId=t.detail.value,this.refresh()}}"
                        ></or-mwc-input>
                        <div class="attributes">
                            ${this.query.attributes&&this.query.attributes.items?this.query.attributes.items.map((t,r)=>e`
                                    ${r>0?e`<or-icon class="small" icon="ampersand"></or-icon>`:""}
                                    <div class="attribute">
                                        <div>
                                            ${this.attributePredicateEditorTemplate(i,"*"!==n?this._assets.find(t=>t.id===n):void 0,t)}
                                            ${this.attributeDurationTemplate(this.duration,r,s,u)}
                                        </div>
                                    ${a?e`
                                        <button class="button-clear" @click="${()=>this.removeAttributePredicate(this.query.attributes,t)}"><or-icon icon="close-circle"></or-icon></input>
                                    </div>`:""}
                                `):""}
                            ${r?e`
                                <or-mwc-input class="plus-button" type="${d.BUTTON}" icon="plus"
                                              label="rulesEditorAddAttribute" @or-mwc-input-changed="${t=>this.addAttributePredicate(this.query.attributes)}"></or-mwc-input>
                            `:""}
                        </div>
                    `})}
            </div>
        `}set _assetId(t){t&&"*"!==t?this.query.ids=[t]:this.query.ids=void 0,this.dispatchEvent(new h),this.requestUpdate()}getAttributeName(t){return t&&t.name?t.name.value:void 0}setAttributeName(t,e){t.name||(t.name={predicateType:"string"}),t.name.match="EXACT",t.name.value=e,t.value=void 0,this.dispatchEvent(new h),this.requestUpdate()}getOperatorMapValue(t,e,r,i,a){if(e&&r&&t[e+":"+r])return t[e+":"+r];if(a){if(t[a.name])return t[a.name];if(t[a.jsonType])return t[a.jsonType];if(a.arrayDimensions)return t.array}}getOperators(t,e,r,i,a){let s;return this.config&&this.config.controls&&this.config.controls.allowedAssetQueryOperators&&(s=this.getOperatorMapValue(this.config.controls.allowedAssetQueryOperators,l(this.query),a,e,r)),s||(s=this.getOperatorMapValue(this._queryOperatorsMap,l(this.query),a,e,r)),s?s.map(t=>[t,c.t(t)]):[]}getOperator(t){if(!t)return;if(void 0!==t.timestampOlderThan)return o.NOT_UPDATED_FOR;if(!t.value)return;let e=t.value;switch(e.predicateType){case"string":switch(e.match){case"EXACT":return e.negate?o.NOT_EQUALS:o.EQUALS;case"BEGIN":return e.negate?o.NOT_STARTS_WITH:o.STARTS_WITH;case"END":return e.negate?o.NOT_ENDS_WITH:o.ENDS_WITH;case"CONTAINS":return e.negate?o.NOT_CONTAINS:o.CONTAINS}return;case"boolean":return e.value?o.IS_TRUE:o.IS_FALSE;case"datetime":case"number":switch(e.operator){case"EQUALS":return e.negate?o.NOT_EQUALS:o.EQUALS;case"GREATER_THAN":return e.negate?o.LESS_EQUALS:o.GREATER_THAN;case"GREATER_EQUALS":return e.negate?o.LESS_THAN:o.GREATER_EQUALS;case"LESS_THAN":return e.negate?o.GREATER_EQUALS:o.LESS_THAN;case"LESS_EQUALS":return e.negate?o.GREATER_THAN:o.LESS_EQUALS;case"BETWEEN":return e.negate?o.NOT_BETWEEN:o.BETWEEN}return;case"radial":return e.negated?o.OUTSIDE_RADIUS:o.WITHIN_RADIUS;case"rect":return e.negated?o.OUTSIDE_RECTANGLE:o.WITHIN_RECTANGLE;case"array":if(e.value&&e.index)return e.negated?o.NOT_INDEX_CONTAINS:o.INDEX_CONTAINS;if(e.lengthEquals)return e.negated?o.NOT_LENGTH_EQUALS:o.LENGTH_EQUALS;if(e.lengthGreaterThan)return e.negated?o.LENGTH_LESS_THAN:o.LENGTH_GREATER_THAN;if(e.lengthLessThan)return e.negated?o.LENGTH_GREATER_THAN:o.LENGTH_LESS_THAN;return e.negated?o.NOT_CONTAINS:o.CONTAINS;case"value-empty":return e.negate?o.VALUE_NOT_EMPTY:o.VALUE_EMPTY}}updateDurationMap(t){if(this.duration){let e=Array.from(this.duration.entries()).filter(([e,r])=>e!==t).map(([e,r])=>[e>t?e-1:e,r]);this.duration=new Map(e)}}setOperator(t,e,r,i,a){let s;if(!this.query||!this.query.attributes||!this.query.attributes.items||0===this.query.attributes.items.length)return;if(!a){i.value=void 0,this.dispatchEvent(new h),this.requestUpdate();return}let u=n.getAttributeAndValueDescriptors(t.name,e||r);if(!u||!u[1]||!a){i.value=void 0,this.dispatchEvent(new h),this.requestUpdate();return}i.timestampOlderThan=void 0;let l=u[1];switch(a){case o.INDEX_CONTAINS:case o.NOT_INDEX_CONTAINS:case o.LENGTH_EQUALS:case o.NOT_LENGTH_EQUALS:case o.LENGTH_LESS_THAN:case o.LENGTH_GREATER_THAN:l.arrayDimensions&&(s={predicateType:"array",negated:a===o.NOT_INDEX_CONTAINS||a===o.NOT_LENGTH_EQUALS,index:a===o.INDEX_CONTAINS||a===o.NOT_INDEX_CONTAINS?0:void 0,lengthEquals:a===o.LENGTH_EQUALS||a===o.NOT_LENGTH_EQUALS?0:void 0,lengthGreaterThan:a===o.LENGTH_GREATER_THAN?0:void 0,lengthLessThan:a===o.LENGTH_GREATER_THAN?0:void 0});break;case o.WITHIN_RADIUS:case o.OUTSIDE_RADIUS:s={predicateType:"radial",negated:a===o.OUTSIDE_RADIUS,lat:0,lng:0,radius:50};break;case o.WITHIN_RECTANGLE:case o.OUTSIDE_RECTANGLE:s={predicateType:"rect",negated:a===o.OUTSIDE_RECTANGLE,latMin:-.1,lngMin:-.1,latMax:.1,lngMax:.1};break;case o.IS_TRUE:case o.IS_FALSE:if("boolean"===l.jsonType){s={predicateType:"boolean",value:a===o.IS_TRUE};break}case o.STARTS_WITH:case o.NOT_STARTS_WITH:"string"===l.jsonType&&(s={predicateType:"string",negate:a===o.NOT_STARTS_WITH,match:"BEGIN"});break;case o.ENDS_WITH:case o.NOT_ENDS_WITH:"string"===l.jsonType&&(s={predicateType:"string",negate:a===o.NOT_ENDS_WITH,match:"END"});break;case o.NOT_BETWEEN:s="number"===l.jsonType||"bigint"===l.jsonType?{predicateType:"number",operator:"BETWEEN",negate:!0}:{predicateType:"datetime",operator:"BETWEEN",negate:!0};break;case o.GREATER_THAN:case o.GREATER_EQUALS:case o.LESS_THAN:case o.LESS_EQUALS:case o.BETWEEN:let d=p.getEnumKeyAsString(o,a);s="number"===l.jsonType?{predicateType:"number",operator:d}:{predicateType:"datetime",operator:d};break;case o.EQUALS:case o.NOT_EQUALS:"date"===l.jsonType?s={predicateType:"datetime",negate:a===o.NOT_EQUALS,operator:"EQUALS"}:"number"===l.jsonType?s={predicateType:"number",negate:a===o.NOT_EQUALS,operator:"EQUALS"}:"string"===l.jsonType&&(s={predicateType:"string",negate:a===o.NOT_EQUALS,match:"EXACT"});break;case o.VALUE_EMPTY:s={predicateType:"value-empty"};break;case o.VALUE_NOT_EMPTY:s={predicateType:"value-empty",negate:!0};break;case o.CONTAINS:case o.NOT_CONTAINS:l.arrayDimensions?s={predicateType:"array",negated:a===o.NOT_CONTAINS}:"string"===l.jsonType&&(s={predicateType:"string",negate:a===o.NOT_CONTAINS,match:"CONTAINS"});break;case o.NOT_UPDATED_FOR:i.timestampOlderThan="";let c=this.query.attributes.items.indexOf(i);this.updateDurationMap(c)}i.value=s,this.dispatchEvent(new h),this.requestUpdate()}get attributePredicate(){return this.query&&this.query.attributes&&this.query.attributes.items&&this.query.attributes.items.length>0?this.query.attributes.items[0]:void 0}setValuePredicateProperty(t,e,r){t&&(t[e]=r,this.dispatchEvent(new h),this.requestUpdate())}removeAttributePredicate(t,e){let r=t.items.indexOf(e);r>=0&&(t.items.splice(r,1),this.updateDurationMap(r)),this.dispatchEvent(new h),this.requestUpdate()}addAttributePredicate(t){t.items||(t.items=[]),t.items.push({}),this.dispatchEvent(new h),this.requestUpdate()}toggleAttributeGroup(t){"OR"===t.operator?t.operator="AND":t.operator="OR",this.dispatchEvent(new h),this.requestUpdate()}loadAssets(t){this.assetProvider(t).then(t=>{this._assets=t})}};__decorate([a({type:Object,attribute:!1})],OrRuleAssetQuery.prototype,"condition",void 0),__decorate([a({type:Object})],OrRuleAssetQuery.prototype,"config",void 0),__decorate([a({type:Object})],OrRuleAssetQuery.prototype,"assetInfos",void 0),__decorate([a({type:Object})],OrRuleAssetQuery.prototype,"assetProvider",void 0),__decorate([s()],OrRuleAssetQuery.prototype,"_assets",void 0),OrRuleAssetQuery=__decorate([i("or-rule-asset-query")],OrRuleAssetQuery);export{OrRuleAssetQuery};