import{composeWithUi as e,createDefaultValue as t,deriveTypes as r,getAjv as o,getData as i,getRenderers as n,getSchema as s,hasShowRule as a,isVisible as c,Resolve as l}from"@jsonforms/core";import{DefaultColor5 as m,Util as p}from"@openremote/core";import{InputType as d}from"@openremote/or-mwc-components/or-mwc-input";import{i18next as f}from"@openremote/or-translate";import"@openremote/or-components/or-ace-editor";import{html as u,unsafeCSS as h}from"lit";import{createRef as b,ref as v}from"lit/directives/ref.js";import{unknownTemplate as S}from"./standard-renderers";import{OrMwcDialog as g,showDialog as y}from"@openremote/or-mwc-components/or-mwc-dialog";export function getTemplateFromProps(e,t){let r;if(!e||!t)return u``;let o=t.renderers||n({jsonforms:Object.assign({},e)}),i=t.schema,s=t.uischema;if(o&&i&&s&&e.core){let n=o.map(t=>[t,t.tester(s,i,{rootSchema:resolveSubSchemasRecursive(i,e.core.schema),config:e.config})]).sort((e,t)=>t[1]-e[1]),a=n&&n.length>0?n[0]:void 0;r=a&&-1!==a[1]?a[0].renderer(e,t):S()}return r}export function getCombinatorInfos(e,o){return e.map(e=>{let i,n,s,a=findSchemaTitleAndDescription(e,o);if(e.$ref&&(e=l.schema(e,"",o)),Array.isArray(e.allOf)&&(e=l.schema(e,"allOf",o)),r(e).every(e=>"object"===e)){let r=getSchemaObjectProperties(e).find(([e,t])=>void 0!==getSchemaConst(t));r?(i=r[0],n=getSchemaConst(r[1]),s=()=>{let e={};return e[r[0]]=getSchemaConst(r[1]),e},a[0]||(a[0]=getSchemaConst(r[1]))):s=()=>t(e,o)}else s=()=>t(e,o);return{title:a[0],description:a[1],defaultValueCreator:s,constProperty:i,constValue:n}})}export function getSchemaConst(e){if(e){if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&1===e.enum.length)return e.enum[0]}}export function getSchemaPicker(e,t,r,o,i,n){let s=getCombinatorInfos(t[o],e),a=s.map((e,t)=>[t+"",e.title||f.t("schema.title.indexedItem",{index:t})]),c=i?f.t("schema.anyOfPickerLabel",{label:i}):f.t("type");return u`                
        <or-mwc-input class="any-of-picker" .label="${c}" .type="${d.SELECT}" .options="${a}" @or-mwc-input-changed="${e=>{n(s[Number(e.detail.value)])}}"></or-mwc-input>
    `}export function findSchemaTitleAndDescription(e,t){let r;if(e.$ref&&(r=getLabelFromScopeOrRef(e.$ref),e=l.schema(e,"",t)),e.title)return[e.title,e.description];if(e.allOf){let r=l.schema(e,"allOf",t).allOf.find(e=>!!e.title);if(r)return[r.title,r.description]}return[f.t("schema.title."+r,{defaultValue:p.camelCaseToSentenceCase(r)}),void 0]}function getLabelFromScopeOrRef(e){return e.substr(e.lastIndexOf("/")+1)}function getSchemaObjectProperties(e){let t=[];return e.allOf?t=e.allOf.map(e=>e.properties?Object.entries(e.properties):[]).flat():e.properties&&(t=Object.entries(e.properties)),t}export function mapStateToCombinatorRendererProps(t,r,n){let{uischema:m}=r,p=e(m,r.path),d=s(t),f=l.schema(r.schema||d,m.scope,d),u=void 0===r.visible||a(m)?c(m,i(t),r.path,o(t)):r.visible,h=r.id,b=l.data(i(t),p),v=t.jsonforms.core.ajv,S=f||d,g=l.schema(S,n,d),y=["required","additionalProperties","type","enum","const"],O=e=>!e||0===e.length||!e.find(e=>-1!==y.indexOf(e.keyword)),w=-1;for(let e=0;e<g.length;e++)try{let t=Object.assign({definitions:d.definitions},g[e]),r=v.compile(t);if(r(b),O(r.errors)){w=e;break}}catch(e){console.debug("Combinator subschema is not self contained, can't hand it over to AJV")}return{data:b,path:p,schema:S,rootSchema:d,visible:u,id:h,indexOfFittingSchema:w,uischemas:t.jsonforms.uischemas,uischema:m}}export function getLabel(e,t,r,o){if(r)return r;let i=findSchemaTitleAndDescription(e,t);return i[0]?i[0]:o?p.camelCaseToSentenceCase(getLabelFromScopeOrRef(o)):void 0}export function resolveSubSchemasRecursive(e,t,r){return e.$ref?resolveSubSchemasRecursive(l.schema(t,e.$ref,t),t):((r?[r]:["allOf","anyOf","oneOf"]).forEach(r=>{let o=e[r];o&&(e[r]=o.map(e=>resolveSubSchemasRecursive(e,t)))}),e.items&&(Array.isArray(e.items)?e.items=e.items.map(e=>resolveSubSchemasRecursive(e,t)):e.items=resolveSubSchemasRecursive(e.items,t)),e.properties&&Object.keys(e.properties).forEach(r=>e.properties[r]=resolveSubSchemasRecursive(e.properties[r],t)),e)}export const controlWithoutLabel=e=>({type:"Control",scope:e,label:!1});export const showJsonEditor=(e,t,r)=>{let o=b(),i=b();y(new g().setContent(u`
                <or-ace-editor ${v(o)} @or-ace-editor-edit="${()=>void(i.value.disabled=!0)}" @or-ace-editor-changed="${e=>(e=>{let t=e.detail.valid;i.value.disabled=!t})(e)}" .value="${t}"></or-ace-editor>
            `).setActions([{actionName:"cancel",content:"cancel"},{default:!0,actionName:"update",action:()=>{let e=o.value;e.validate()&&r(e.getValue()?JSON.parse(e.getValue()):void 0)},content:u`<or-mwc-input ${v(i)} disabled .type="${d.BUTTON}" label="update"></or-mwc-input>`}]).setHeading(e).setDismissAction(null).setStyles(u`
                <style>
                    .mdc-dialog__surface {
                        width: 1024px;
                        overflow-x: visible !important;
                        overflow-y: visible !important;
                    }
                    #dialog-content {
                        border-color: var(--or-app-color5, ${h(m)});
                        border-top-width: 1px;
                        border-top-style: solid;
                        border-bottom-width: 1px;
                        border-bottom-style: solid;
                        padding: 0;
                        overflow: visible;
                        height: 60vh;
                    }
                </style>
            `))};