import{toObject}from"./flatTool";import{isPlainObject}from"../validator";import{canUseVirtualHost}from"../version";const RawLifeCycles=["Created","Attached","Ready","Moved","Detached","Error"],NativeLifeCycles=RawLifeCycles.map(e=>e.toLowerCase()),ComponentNativeProps=["properties","data","observers","methods","behaviors",...NativeLifeCycles,"relations","externalClasses","options","lifetimes","pageLifeTimes","definitionFilter"];export const toComponent=function(e){const{relations:t,behaviors:o=[],externalClasses:i=[]}=e;if(e.properties){Object.keys(e.properties).forEach(t=>{let o=e.properties[t];isPlainObject(o)||(o={type:o}),e.properties[t]=o});[{key:"ariaHidden",type:Boolean},{key:"ariaRole",type:String},{key:"ariaLabel",type:String},{key:"ariaLabelledby",type:String},{key:"ariaDescribedby",type:String},{key:"ariaBusy",type:Boolean}].forEach(({key:t,type:o})=>{e.properties[t]={type:o}}),e.properties.style={type:String,value:""},e.properties.customStyle={type:String,value:""}}e.methods||(e.methods={}),e.lifetimes||(e.lifetimes={});const s={};if(t){const e=(e,t)=>Behavior({created(){Object.defineProperty(this,`$${e}`,{get:()=>{const o=this.getRelationNodes(t)||[];return"parent"===e?o[0]:o}})}}),i={};Object.keys(t).forEach(o=>{const s=t[o],r=["parent","ancestor"].includes(s.type)?"parent":"children",n=e(r,o);i[r]=n}),o.push(...Object.keys(i).map(e=>i[e]))}if(e.behaviors=[...o],e.externalClasses=["class",...i],Object.getOwnPropertyNames(e).forEach(t=>{const o=Object.getOwnPropertyDescriptor(e,t);o&&(NativeLifeCycles.indexOf(t)<0&&"function"==typeof o.value?(Object.defineProperty(e.methods,t,o),delete e[t]):ComponentNativeProps.indexOf(t)<0?s[t]=o:NativeLifeCycles.indexOf(t)>=0&&(e.lifetimes[t]=e[t]))}),Object.keys(s).length){const t=e.lifetimes.created,o=e.lifetimes.attached,{controlledProps:i=[]}=e;e.lifetimes.created=function(...e){Object.defineProperties(this,s),t&&t.apply(this,e)},e.lifetimes.attached=function(...e){o&&o.apply(this,e),i.forEach(({key:e})=>{const t=`default${e.replace(/^(\w)/,(e,t)=>t.toUpperCase())}`,o=this.properties;null==o[e]&&(this._selfControlled=!0),null==o[e]&&null!=o[t]&&this.setData({[e]:o[t]})})},e.methods._trigger=function(e,t,o){const s=i.find(t=>t.event===e);if(s){const{key:e}=s;this._selfControlled&&this.setData({[e]:t[e]})}this.triggerEvent(e,t,o)}}return e};export const wxComponent=function(){return function(e){const t=new class extends e{};t.options=t.options||{},canUseVirtualHost()&&(t.options.virtualHost=!0);const o=toComponent(toObject(t));Component(o)}};