/**
 * Copyright 2019 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as e,html as t,css as r}from"../../../lit/index.js";import"./simple-fields-container.js";import"./simple-fields-fieldset.js";import"./simple-fields-array.js";class SimpleFieldsLite extends e{static get styles(){return[r`
        :host {
          display: block;
          font-family: var(
            --simple-fields-detail-font-family,
            var(--simple-fields-font-family, sans-serif)
          );
          font-size: var(
            --simple-fields-detail-font-size,
            var(--simple-fields-font-size, 12px)
          );
          background: var(--simple-fields-background-color, transparent);
        }
        :host([hidden]) {
          display: none;
        }
      `]}render(){return t`
      <div id="schema-fields" aria-live="polite" part="fields-list">
        <slot></slot>
      </div>
    `}static get properties(){return{...super.properties,disableAutofocus:{type:Boolean},error:{type:Object},language:{type:String,attribute:"lang",reflect:!0},resources:{type:Object},schema:{type:Object},elementizer:{type:Object},value:{type:Object},__delayedFocus:{type:Boolean},__formElements:{type:Object},__formElementsArray:{type:Array}}}static get tag(){return"simple-fields-lite"}constructor(){super(),globalThis.WCGlobalBasePath?this.basePath=globalThis.WCGlobalBasePath:this.basePath=new URL("./simple-fields-lite.js",import.meta.url).href+"/../../../../",this.disableAutofocus=!1,this.language="en",this.resources={},this.schemaConversion,this.__formElements={},this.__formElementsArray=[],this.schema={},this.value={}}disconnectedCallback(){this._clearForm(),super.disconnectedCallback()}updated(e){super.updated&&super.updated(e),e.forEach(((e,t)=>{"error"===t&&this.error!==e&&this._errorChanged(),["schema","schemaConversion"].includes(t)&&this._schemaChanged(this.schema,e),"value"===t&&this._valueChanged(this.value,e)}))}get formElements(){return this.__formElements}get formElementsArray(){return this.__formElementsArray}get schemaConversion(){return this.elementizer||{defaultSettings:{element:"input",attributes:{type:"text"},properties:{minLength:"minlength",maxLength:"maxlength"}},type:{array:{defaultSettings:{element:"simple-fields-array",invalidProperty:"invalid",noWrap:!0,descriptionProperty:"description",child:{element:"simple-fields-array-item",noWrap:!0,descriptionProperty:"description",properties:{previewBy:"previewBy"}}}},boolean:{defaultSettings:{element:"input",valueProperty:"checked",valueChangedProperty:"click",attributes:{type:"checkbox",value:!1}}},file:{defaultSettings:{element:"input",attributes:{type:"url"}}},integer:{defaultSettings:{element:"input",attributes:{autofocus:!0,step:1,type:"number"},properties:{minimum:"min",maximum:"max",multipleOf:"step"}}},markup:{defaultSettings:{element:"textarea"}},number:{defaultSettings:{element:"input",attributes:{autofocus:!0,type:"number"},properties:{minimum:"min",maximum:"max",multipleOf:"step"}}},object:{defaultSettings:{element:"simple-fields-fieldset",noWrap:!0,descriptionProperty:"description"}},string:{format:{"date-time":{defaultSettings:{element:"input",attributes:{autofocus:!0,type:"datetime-local"}}},time:{defaultSettings:{element:"input",attributes:{autofocus:!0,type:"time"}}},date:{defaultSettings:{element:"input",attributes:{autofocus:!0,type:"date"}}},email:{defaultSettings:{element:"input",attributes:{autofocus:!0,type:"email"}}},uri:{defaultSettings:{element:"input",attributes:{autofocus:!0,type:"url"}}}}}}}}get valid(){return!this.error||0===Object.keys(this.error||{}).length}updateSchema(){this._formFieldsChanged()}getFormElementById(e){return(this.__formElementsArray||[]).filter((t=>t.id===e))[0]}focus(){let e=!!(this.__formElementsArray&&this.__formElementsArray[0]&&this.__formElementsArray[0].field)&&this.__formElementsArray[0].field;e?(e.focus(),this.__delayedFocus=!1):this.__delayedFocus=!0}rebuildForm(){this._clearForm(),this._addToForm();let e=!!(this.__formElementsArray&&this.__formElementsArray[0]&&this.__formElementsArray[0].field)&&this.__formElementsArray[0].field;e&&(e.autofocus=!this.disableAutofocus),!this.__delayedFocus&&this.disableAutofocus||this.focus(),this.dispatchEvent(new CustomEvent("fields-ready",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}_addToForm(e=this.schema,t=this,r="",i){let s=e.properties,l=e.required;Object.keys(s||{}).forEach((a=>{let o=s[a],n=i||this._convertSchema(o);if(n&&n.element){let i=`${r}${a}`,s=globalThis.document.createElement(n.element),d=o.properties||o.items||o.noWrap||n.noWrap?s:globalThis.document.createElement("simple-fields-container"),p=this._getValue(`${r}${a}`),m=!(!Object.getPrototypeOf(s)&&!Object.getPrototypeOf(s).constructor)&&Object.getPrototypeOf(s).constructor.properties;Object.keys(m||{}).forEach((e=>{o[e]&&(s[e]=o[e])})),!globalThis.customElements.get(n.element)&&n.import?import(`${this.basePath}${n.import}`):globalThis.customElements.get(n.element)||console.warn(`missing field: ${n.element}`);let h=o.label||o.title||o.description||a,u=o.prefix,c=o.suffix,f=o.description&&(o.label||o.title)?o.description:void 0,y=(o.onValueChanged,o.onErrorChanged);n.labelSlot=e.labelSlot||n.labelSlot,n.descriptionSlot=e.descriptionSlot||n.descriptionSlot,n.errorMessageSlot=e.errorMessageSlot||n.errorMessageSlot,n.prefixSlot=e.prefixSlot||n.prefixSlot||"prefix",n.suffixSlot=e.suffixSlot||n.suffixSlot||"suffix",n.valueSlot=e.valueSlot||n.valueSlot,n.labelProperty=e.labelProperty||n.labelProperty||"label",n.descriptionProperty=e.descriptionProperty||n.descriptionProperty||"description",n.valueProperty=e.valueProperty||n.valueProperty||"value",n.setValueProperty=e.setValueProperty||n.setValueProperty||n.valueProperty,n.valueChangedProperty=e.valueChangedProperty||n.valueChangedProperty||`${n.valueProperty}-changed`,n.errorProperty=e.errorProperty||n.errorProperty||"error",n.errorChangedProperty=e.errorChangedProperty||n.errorChangedProperty||`${n.errorProperty}-changed`,n.errorMessageProperty=e.errorMessageProperty||n.errorMessageProperty||"errorMessage",s.resources=this.resources,s.id=i,s.setAttribute("name",i),s.setAttribute("language",this.language),o.options&&(s.options=o.options),o.itemsList&&(s.itemsList=o.itemsList),l&&l.includes(a)&&s.setAttribute("required",!0),o.disabled&&(d.disabled=!0),o.hidden&&(d.hidden=!0),o.readonly&&(s.hidden=!0,d.hidden=!0),this._configElement(d,h,n.labelProperty,n.labelSlot),this._configElement(d,f,n.descriptionProperty,n.descriptionSlot),this._configElement(d,u,void 0,n.prefixSlot),this._configElement(d,c,void 0,n.suffixSlot),Object.keys(n.attributes||{}).forEach((e=>{void 0!==typeof n.attributes[e]&&null!==n.attributes[e]&&s.setAttribute(e,n.attributes[e])})),Object.keys(n.properties||{}).forEach((e=>{n.properties[e]&&o[e]&&(s[e]||(s[e]=o[e]||n.properties[e]))})),Object.keys(n.slots||{}).forEach((e=>{n.slots[e]&&o[n.slots[e]]&&n.slots[e].split(/[\s,]/).forEach((t=>{let r=globalThis.document.createElement("span");r.slot=e,r.innerHTML=o[t],s.appendChild(r)}))})),t.slots&&t.slots[a]&&(d.slot=t.slots[a]),t.appendChild(d),"array"===o.type?this._addArrayItems(p||[],n.child,o,s):o.properties?this._addToForm(o,s,`${s.id}.`,n.child):(s!==d&&(s.slot="field",d.appendChild(s)),void 0===p&&"boolean"!==o.type||this._configElement(s,p,n.setValueProperty,n.valueSlot),s.addEventListener(n.valueChangedProperty,(e=>this._handleChange(s,n.valueProperty,e))),d.addEventListener(n.errorChangedProperty,(e=>{let t=this._deepClone(this.error||{});d[n.errorProperty]?t[i]=d[n.errorMessageProperty]||"":t&&t[i]&&delete t[i],this.error=t,y&&y(e)}))),this.__formElementsArray.push({id:i,field:d,data:n}),this.__formElements[i]={element:s,field:d}}}))}_configElement(e,t,r,i=!1){if(i){let r=globalThis.document.createElement("span");r.slot=i,t&&(r.innerHTML=t),e&&e.querySelectorAll(`[slot=${i}]`).forEach((e=>e.remove())),e.appendChild(r)}else r&&(e[r]=t)}_insertArrayItem(e,t,r,i,s,l){let a=this._getValue(i.name),o=a?a.length:0;a||this._setValue(i.name,[]),l=l||0===l?l:o;let n={properties:{}};n.properties[l]=this._addArrayItem(l,e,t,i),this._setValue(`${i.name}.${l}`,s),this._addToForm(n,i,`${i.id}.`,r)}_addArrayItems(e,t,r,i){let s=Object.keys(r.items.properties||{}),l=r.previewBy||(s.length>0?[s[0]]:void 0);Array.from(e).forEach(((e,s)=>{this._insertArrayItem(r,l,t,i,e,s)})),i.addEventListener("add",(e=>{this._insertArrayItem(r,l,t,i,{})})),i.addEventListener("copy",(e=>{let s=this._getValue(e.detail.name);this._insertArrayItem(r,l,t,i,s),i.insertBefore(i.lastElementChild,e.detail.nextElementSibling),this._reorderArrayItems(i)})),i.addEventListener("reorder",(e=>{this._reorderArrayItems(i)})),i.addEventListener("remove",(e=>{let s=e.detail.id,a=this._getValue(i.name)||[],o=s.replace(`${i.name}.`,"");a.splice(parseInt(o),1),this.__formElementsArray=this.__formElementsArray.filter((e=>0===e.id.indexOf(i.name))),i.innerHTML="",a.forEach(((e,s)=>this._insertArrayItem(r,l,t,i,e,s))),this._setValue(`${i.name}`,a),i.focus(parseInt(o)-1)}))}_reorderArrayItems(e){let t=[...Array.from(this._getValue(e.name))||[]],updateIndex=(e,t,r)=>{e.id&&(e.id=e.id.replace(t,r)),e.name&&(e.name=e.name.replace(t,r)),[...e.childNodes].forEach((e=>updateIndex(e,t,r)))},r=[...Array.from(e.childNodes)],i=[];r.forEach(((e,r)=>{if(!e.isArrayItem)return;let s=e.id.replace(/\.\d+$/,""),l=parseInt(e.id.replace(/.*\./g,""));updateIndex(e,e.id,`${s}.${r}`),i.push(JSON.parse(JSON.stringify(t[l])))})),this._setValue(`${e.name}`,i)}_addArrayItem(e,t,r,i={}){let s=this._deepClone(t.items);return s.label=`${parseInt(e)+1}`,s.previewBy=r,s.hideReorder=i.hideReorder,s.hideDuplicate=i.hideDuplicate,s.expanded=i.expanded,s}_clearForm(){this.innerHTML="",this.__formElementsArray=[]}_convertSchema(e,t=this.schemaConversion,r){let i=Object.keys(e||{}),s=Object.keys(t).filter((e=>i.includes(e)));return t.defaultSettings&&(r=this._deepClone(t.defaultSettings)),s.forEach((i=>{let s=e[i],l=t?t[i]:void 0,a=l?Array.isArray(s)?l[s[0]]:l[s]:void 0;a&&(r=this._convertSchema(e,a,r))})),r}_deepClone(e){return JSON.parse(JSON.stringify(e))}_errorChanged(){this.formElementsArray.forEach((e=>{let t=e.data||{},r=e.field;if(e.id&&r&&this.error){let r=this.error[e.id]||!1,i=!!this.error[e.id];i||Object.keys(this.error||{}).forEach((t=>{t.match(e.id)&&(i=!0)})),this._configElement(e.field,r,t.errorMessageProperty,t.errorMessageSlot),e.field[t.errorProperty]=i,e.field.setAttribute("aria-invalid",i)}}))}_fireValueChanged(){this.dispatchEvent(new CustomEvent("value-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}_formFieldsChanged(e){this.dispatchEvent(new CustomEvent("fields-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this}))}_getValue(e){let t=e.split("."),r=this.value;return t.forEach((e=>{r=r&&r[e]?r[e]:void 0})),r}_handleChange(e,t,r){r&&r.stopPropagation&&r.stopPropagation();let i=e.id||e.getAttribute("id"),s=e[t];this._setValue(i,s),this.dispatchEvent(new CustomEvent(`${i}-value-changed`,{bubbles:!0,cancelable:!0,composed:!0,detail:{id:i,element:e,value:s}})),this._fireValueChanged()}_schemaChanged(e,t){e&&e!==t&&(setTimeout((()=>{this.rebuildForm()}),10),this.dispatchEvent(new CustomEvent("schema-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:this})))}_setValue(e,t){let r=this._deepClone(this.value),i=this.value,s=e?e.split("."):[],l=s.length;for(var a=0;a<l-1;a++){let e=s[a];i[e]||(i[e]={}),i=i[e]}i[s[l-1]]=t,this._valueChanged(this.value,r)}_valueChanged(e,t){e&&e!==t&&this._fireValueChanged()}}customElements.define(SimpleFieldsLite.tag,SimpleFieldsLite);export{SimpleFieldsLite};