var __decorate=this&&this.__decorate||function(t,e,i,r){var s,o=arguments.length,a=o<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,i,r);else for(var p=t.length-1;p>=0;p--)(s=t[p])&&(a=(o<3?s(a):o>3?s(e,i,a):s(e,i))||a);return o>3&&a&&Object.defineProperty(e,i,a),a},__awaiter=this&&this.__awaiter||function(t,e,i,r){return new(i||(i=Promise))(function(s,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function p(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){var e;t.done?s(t.value):((e=t.value)instanceof i?e:new i(function(t){t(e)})).then(a,p)}u((r=r.apply(t,e||[])).next())})};import{css as t,html as e,LitElement as i}from"lit";import{customElement as r,property as s}from"lit/decorators.js";import{ifDefined as o}from"lit/directives/if-defined.js";import{until as a}from"lit/directives/until.js";import{createRef as p,ref as u}from"lit/directives/ref.js";import{when as n}from"lit/directives/when.js";import{i18next as l,translate as d}from"@openremote/or-translate";import{AssetModelUtil as h}from"@openremote/model";import c,{subscribe as m,Util as b}from"@openremote/core";import{getValueHolderInputTemplateProvider as v,InputType as _}from"@openremote/or-mwc-components/or-mwc-input";import{progressCircular as f}from"@openremote/or-mwc-components/style";import"@openremote/or-components/or-loading-wrapper";import{geoJsonPointInputTemplateProvider as y}from"@openremote/or-map";import{StandardRenderers as g}from"@openremote/or-json-forms";import{agentIdRendererRegistryEntry as w}from"./renderers/agent-link";import{schedulerRendererRegistryEntry as T}from"./renderers/scheduler";export class OrAttributeInputChangedEvent extends CustomEvent{constructor(t,e){super(OrAttributeInputChangedEvent.NAME,{detail:{value:t,previousValue:e},bubbles:!0,composed:!0})}}OrAttributeInputChangedEvent.NAME="or-attribute-input-changed";export function getAttributeInputWrapper(t,i,r,s,a,p,u,n,l){return a&&(t=e`
                    <div id="wrapper-helper">
                        ${p?e`<div id="wrapper-label">${p}</div>`:""}
                        <div id="wrapper-input">${t}</div>
                        <div id="helper-text">${a}</div>
                    </div>
                `),u&&(t=e`
                ${t}
                <or-mwc-input id="send-btn" icon="${u}" type="button" .disabled="${s||r}" @or-mwc-input-changed="${t=>{t.stopPropagation(),n&&n()}}"></or-mwc-input>
            `),e`
            <div id="wrapper" style="width: 100%" class="${u||l?"no-padding":"right-padding"}">
                ${t}
                <div id="scrim" class="${o(r?void 0:"hidden")}"><progress class="pure-material-progress-circular"></progress></div>
            </div>
        `}export function getHelperText(t,e,i){return t?l.t("sending"):e?l.t("sendFailed"):i?l.t("updatedWithDate",{date:new Date(i)}):void 0}let jsonFormsAttributeRenderers=[...g,w,T],schemas=new Map,inflightRequests=new Map;function getSchema(t){return __awaiter(this,void 0,void 0,function*(){var e;let i=t.name+"[]".repeat(null!=(e=t.arrayDimensions)?e:0);if(schemas.has(i))return schemas.get(i);if(inflightRequests.has(i))return inflightRequests.get(i);let r=c.rest.api.AssetModelResource.getValueDescriptorSchema({name:i}).then(t=>{let e=t.data;return schemas.set(i,e),e}).finally(()=>inflightRequests.delete(i));return inflightRequests.set(i,r),r})}export const jsonFormsInputTemplateProvider=(t,i)=>(r,s,o,a,l,d)=>{if(b.isComplexValueDescriptor(a)){let t,r,s=!!(d&&d.disabled),o=!!(d&&d.readonly),h=d.label,c={type:"Control",scope:"#"},m=p(),v=p(),f=!1,y=t=>{var e;if(f&&!b.objectsEqual(t.data,r)){r=t.data;let i=!!(null==(e=t.errors)?void 0:e.length);l({value:t.data,errors:i})}};return{templateFunction:(p,d,b,g,w,T)=>(window.setTimeout(()=>__awaiter(void 0,void 0,void 0,function*(){if(f||(r=p),f=!0,t=yield getSchema(a),m.value&&v.value){let e=m.value;e.schema=t,e.data=p,v.value.loading=!1}}),0),e`
                <style>
                    .disabled {
                        opacity: 0.5;
                        pointer-events: none;
                    }
                    or-loading-wrapper {
                        width: 100%;
                    }
                    or-json-forms {
                        max-width: 100%;
                        min-width: 0; /* Allows the element to shrink */
                    }
                    #clear {
                        width: unset !important;
                    }
                </style>
                <or-loading-wrapper ${u(v)} .loading="${!0}">
                    <div style="display: flex; width: 100%">
                    <or-json-forms .renderers="${jsonFormsAttributeRenderers}" ${u(m)}
                                   .disabled="${s}" .readonly="${o}" .label="${h}"
                                   .schema="${t}" .uischema="${c}" .onChange="${y}">
                    </or-json-forms>
                    ${n(i,()=>e`
                        <or-mwc-input id="clear" outlined .type="${_.BUTTON}" icon="backspace" @or-mwc-input-changed="${()=>l({value:null})}"></or-mwc-input>
                    `)}
                    </div>
                </or-loading-wrapper>
            `),supportsHelperText:!1,supportsLabel:!1,supportsSendButton:!1,validator:()=>!!m.value&&m.value.checkValidity()}}return t};let DEFAULT_TIMEOUT=5e3,OrAttributeInput=class extends m(c)(d(l)(i)){constructor(){super(...arguments),this.disableSubscribe=!1,this.disableWrite=!1,this.compact=!1,this.comfortable=!1,this.resizeVertical=!1,this.writeTimeout=5e3,this._requestFocus=!1,this._sendError=!1,this.langChangedCallback=()=>{this._updateTemplate(),this.requestUpdate()}}static get styles(){return[f,t`
            :host {
                display: inline-block;
            }
            
            :host(.force-btn-padding) #wrapper.no-padding {
                /*padding-right: 52px;*/
            }   
            
            #wrapper or-mwc-input, #wrapper or-map {
                width: 100%;
            }
            
            #wrapper or-map {
                min-height: 250px;
            }

            #wrapper .long-press-msg {
                display: none;
            }
            
            #wrapper {
                display: flex;
                position: relative;
            }
            
            #wrapper.right-padding {
                padding-right: 52px;
            }
            
            #wrapper-helper {
                display: flex;
                flex: 1;
                flex-direction: column;
                max-width: 100%;
            }
            
            #wrapper-input {
                flex: 1;
                display: flex;
            }
            
            #wrapper-label, #helper-text {
                margin-left: 16px;
            }
            
            /* Copy of mdc text field helper text styles */
            #helper-text {                
                min-width: 255px;
                color: rgba(0, 0, 0, 0.6);
                font-family: Roboto, sans-serif;
                -webkit-font-smoothing: antialiased;
                font-size: 0.75rem;
                font-weight: 400;
                letter-spacing: 0.0333333em;
            }
            
            #scrim {
                position: absolute;
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                background: white;
                opacity: 0.2;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            #scrim.hidden {
                display: none;
            }

            #send-btn { 
                flex: 0;
                margin-left: 4px;
                margin-top: 4px;
            }
        `]}disconnectedCallback(){super.disconnectedCallback(),this._clearWriteTimeout()}shouldUpdate(t){let e=super.shouldUpdate(t),i=!1,r=!1;if(t.has("disableSubscribe")&&(i=!0),(t.has("attributeDescriptor")||t.has("valueDescriptor")||t.has("assetType"))&&(r=!0),t.has("attribute")){let e=Object.assign({},t.get("attribute")),s=this.attribute;if(e&&s){let o=e.value,a=e.timestamp;if(e.value=s.value,e.timestamp=s.timestamp,b.objectsEqual(e,s))if(b.objectsEqual(o,s.value)&&a===s.timestamp){if(1===t.size)return!1}else this._onAttributeValueChanged(o,s.value,s.timestamp);else i=!0,r=!0}}return t.has("assetId")&&t.get("assetId")!==this.assetId&&(i=!0,r=!0),r&&this._updateDescriptors(),i&&this._updateSubscribedRefs(),this._templateProvider&&(t.has("disabled")||t.has("readonly")||t.has("required")||t.has("label"))&&this._updateTemplate(),e}_updateSubscribedRefs(){if(this._attributeEvent=void 0,this.disableSubscribe)this.attributeRefs=void 0;else{let t=this._getAttributeRef();this.attributeRefs=t?[t]:void 0}}_getAttributeRef(){if(this.assetId&&this.attribute)return{name:this.attribute.name,id:this.assetId}}_updateDescriptors(){var t;if(this._valueDescriptor=void 0,this._attributeDescriptor=void 0,this.attributeDescriptor&&this.valueDescriptor)this._attributeDescriptor=this.attributeDescriptor,this._valueDescriptor=this.valueDescriptor;else{let t=this.attributeDescriptor||(this.attribute?this.attribute.name:void 0);if(t){let e=h.getAttributeAndValueDescriptors(this.assetType,t,this.attribute);this._attributeDescriptor=e[0],this._valueDescriptor=this.valueDescriptor?this._valueDescriptor:e[1]}else this._attributeDescriptor=this.attributeDescriptor,this._valueDescriptor=this.valueDescriptor}if(this._valueDescriptor&&"assetType"==this._valueDescriptor.name){let e=null==(t=this._valueDescriptor.constraints)?void 0:t.find(t=>"allowedValues"===t.type);e&&e.allowedValues&&e.allowedValues.sort((t,e)=>t.localeCompare(e))}this._updateTemplate()}_updateTemplate(){if(this._templateProvider=void 0,!this.assetType)return;let t=h.resolveValueDescriptor(this.attribute,this._valueDescriptor||this._attributeDescriptor);if(!t)return;let e={readonly:this.isReadonly(),required:this.required,disabled:this.disabled,compact:this.compact,rounded:this.rounded,outlined:this.outlined,label:this.getLabel(),comfortable:this.comfortable,resizeVertical:this.resizeVertical,inputType:this.inputType},i=t=>{if(null==t?void 0:t.errors)return;let e=t?t.value:void 0,i=t&&t.enterPressed||!this._templateProvider||!this.showButton||!this._templateProvider.supportsSendButton;this._onInputValueChanged(e,i)};if(this.customProvider){this._templateProvider=this.customProvider?this.customProvider(this.assetType,this.attribute,this._attributeDescriptor,t,t=>i(t),e):void 0;return}if("GEO_JSONPoint"===t.name){this._templateProvider=y(this.assetType,this.attribute,this._attributeDescriptor,t,t=>i(t),e);return}let r=v(this.assetType,this.attribute,this._attributeDescriptor,t,t=>i(t),e);this._templateProvider=jsonFormsInputTemplateProvider(r,!0)(this.assetType,this.attribute,this._attributeDescriptor,t,t=>i(t),e),this._templateProvider||(this._templateProvider=r)}getLabel(){let t;if(this.label)t=this.label;else if(""!==this.label&&null!==this.label){let e=h.getAttributeAndValueDescriptors(this.assetType,this.attribute?this.attribute.name:void 0,this._attributeDescriptor);t=b.getAttributeLabel(this.attribute,e[0],this.assetType,!0)}return t}isReadonly(){return c.hasRole("write:attributes")?void 0!==this.readonly?this.readonly:b.getMetaValue("readOnly",this.attribute,this._attributeDescriptor):(this.readonly=!c.hasRole("write:attributes"),this.readonly)}render(){if(!this.assetType||!this._templateProvider)return e``;let t=this.attributeRefs&&!this._attributeEvent||!!this._writeTimeoutHandler,i=this.getValue(),r=this._requestFocus;this._requestFocus=!1;let s=this.hasHelperText?getHelperText(!!this._writeTimeoutHandler,this._sendError,this.getTimestamp()):void 0,o=this.showButton?this._writeTimeoutHandler?"send-clock":"send":this.disableButton?void 0:"";return getAttributeInputWrapper(this._templateProvider&&this._templateProvider.templateFunction?e`${a(this._templateProvider.templateFunction(i,r,t,!!this._writeTimeoutHandler,this._sendError,this._templateProvider.supportsHelperText?s:void 0),"")}`:e`<or-translate .value="attributeUnsupported"></or-translate>`,i,t,!!this.disabled,this._templateProvider.supportsHelperText?void 0:s,this._templateProvider.supportsLabel?void 0:this.getLabel(),this._templateProvider.supportsSendButton?o:void 0,()=>this._updateValue(),this.fullWidth)}updated(t){t.has("_writeTimeoutHandler")&&!this._writeTimeoutHandler&&(this._requestFocus=!0,this.requestUpdate())}get showButton(){return!this.isReadonly()&&!this.disabled&&!this.disableButton&&!!this._getAttributeRef()&&!!this._templateProvider&&this._templateProvider.supportsSendButton}getValue(){return this._attributeEvent?this._attributeEvent.value:this.attribute?this.attribute.value:this.value}getTimestamp(){return this._attributeEvent?this._attributeEvent.timestamp:this.attribute?this.attribute.timestamp:void 0}_onEvent(t){if("attribute"!==t.eventType)return;let e=this.getValue();this._attributeEvent=t,this._onAttributeValueChanged(e,this._attributeEvent.value,t.timestamp)}checkValidity(){return!!this._templateProvider&&(!this._templateProvider.validator||this._templateProvider.validator())}_onAttributeValueChanged(t,e,i){this.attribute&&(this.attribute.value=e,this.attribute.timestamp=i),this._clearWriteTimeout(),this.value=e,this._sendError=!1,this.dispatchEvent(new OrAttributeInputChangedEvent(e,t))}_onInputValueChanged(t,e){this._newValue=t,e&&this._updateValue()}_updateValue(){if(this.readonly||this.isReadonly()||this._writeTimeoutHandler)return;void 0===this._newValue&&(this._newValue=this.getValue());let t=this.getValue(),e=this._newValue;this._newValue=void 0;let i=this._getAttributeRef();i&&!this.disableWrite?(super._sendEvent({eventType:"attribute",ref:i,value:e}),this._writeTimeoutHandler=window.setTimeout(()=>this._onWriteTimeout(),this.writeTimeout)):(this.value=e,this.dispatchEvent(new OrAttributeInputChangedEvent(e,t)))}_clearWriteTimeout(){this._writeTimeoutHandler&&window.clearTimeout(this._writeTimeoutHandler),this._writeTimeoutHandler=void 0}_onWriteTimeout(){this._sendError=!0,(!this.showButton||this.hasHelperText)&&this.requestUpdate("value"),this._clearWriteTimeout()}};__decorate([s({type:Object,reflect:!1})],OrAttributeInput.prototype,"attribute",void 0),__decorate([s({type:String})],OrAttributeInput.prototype,"assetId",void 0),__decorate([s({type:Object})],OrAttributeInput.prototype,"attributeDescriptor",void 0),__decorate([s({type:Object})],OrAttributeInput.prototype,"valueDescriptor",void 0),__decorate([s({type:String})],OrAttributeInput.prototype,"assetType",void 0),__decorate([s({type:String})],OrAttributeInput.prototype,"label",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"disabled",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"readonly",void 0),__decorate([s({type:Boolean,attribute:!0})],OrAttributeInput.prototype,"required",void 0),__decorate([s()],OrAttributeInput.prototype,"value",void 0),__decorate([s()],OrAttributeInput.prototype,"inputType",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"hasHelperText",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"disableButton",void 0),__decorate([s({type:Boolean,attribute:!0})],OrAttributeInput.prototype,"disableSubscribe",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"disableWrite",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"compact",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"comfortable",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"resizeVertical",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"fullWidth",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"rounded",void 0),__decorate([s({type:Boolean})],OrAttributeInput.prototype,"outlined",void 0),__decorate([s()],OrAttributeInput.prototype,"_attributeEvent",void 0),__decorate([s()],OrAttributeInput.prototype,"_writeTimeoutHandler",void 0),OrAttributeInput=__decorate([r("or-attribute-input")],OrAttributeInput);export{OrAttributeInput};