var __decorate=this&&this.__decorate||function(e,t,r,i){var o,a=arguments.length,s=a<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,i);else for(var n=e.length-1;n>=0;n--)(o=e[n])&&(s=(a<3?o(s):a>3?o(t,r,s):o(t,r))||s);return a>3&&s&&Object.defineProperty(t,r,s),s};import{computeLabel as e,createDefaultValue as t,mapDispatchToArrayControlProps as r,Paths as i,Resolve as o,update as a}from"@jsonforms/core";import{css as s,html as n,unsafeCSS as d}from"lit";import{customElement as l,property as m}from"lit/decorators.js";import{controlWithoutLabel as c,getCombinatorInfos as p,getTemplateFromProps as h,showJsonEditor as g}from"../util";import{InputType as f}from"@openremote/or-mwc-components/or-mwc-input";import{i18next as u}from"@openremote/or-translate";import{OrMwcDialog as v,showDialog as b}from"@openremote/or-mwc-components/or-mwc-dialog";import"@openremote/or-mwc-components/or-mwc-list";import{addItemOrParameterDialogStyle as w,baseStyle as y,panelStyle as A}from"../styles";import{DefaultColor4 as I,DefaultColor5 as x}from"@openremote/core";import{ControlBaseElement as $}from"./control-base-element";import{getTemplateWrapper as E}from"../index";let style=s`
    .item-border, .drag-handle {
        border-color: var(--or-app-color5, ${d(x)});
        border-radius: 4px;
        border-width: 1px;
        border-style: solid;
    }

    .item-wrapper {
        display: flex;
    }
    
    .item-wrapper > .item-container {
        flex: 1;
    }

    .item-wrapper + .item-wrapper {
        padding-top: 10px;
    }
    
    .item-wrapper > .item-container > .item-container {
        margin: 0;
        flex: 1;
    }

    .item-wrapper > .item-container > .item-container > .delete-container {
        display: none;
    }

    .item-wrapper > .item-container > .item-container :first-child {
        padding: 0;
        margin: 0;
        flex: 1;
    }

    .item-wrapper.dragging > .item-container {
        opacity: 0.5;
    }

    .item-wrapper.indicator-after {
        border-bottom-width: 3px;
        border-bottom-style: solid;
        border-bottom-color: var(--or-app-color4, ${d(I)});
    }

    .item-wrapper.indicator-before {
        border-top-width: 3px;
        border-top-style: solid;
        border-top-color: var(--or-app-color4, ${d(I)});
    }
    
    .drag-container > button {
        cursor: grab;
    }
`,ControlArrayElement=class extends ${static get styles(){return[y,A,style]}shouldUpdate(e){if(e.has("schema")&&(this.itemInfos=void 0,this.resolvedSchema=o.schema(this.schema,"items",this.rootSchema),Array.isArray(this.resolvedSchema.anyOf)?this.itemInfos=p(this.resolvedSchema.anyOf,this.rootSchema):Array.isArray(this.resolvedSchema.oneOf)&&(this.itemInfos=p(this.resolvedSchema.oneOf,this.rootSchema))),e.has("state")){let e=r(this.state.dispatch);this.addItem=t=>e.addItem(this.path,t)(),this.removeItem=t=>{e.removeItems(this.path,[t])()},this.moveItem=(e,t)=>{this.state.dispatch(a(this.path,r=>{let i,o;return i=1,o=r.splice(e,i)[0],i=0,r.splice(t,i,o),r}))}}return super.shouldUpdate(e)}render(){var t;let r=null!=(t=this.schema.maxItems)?t:Number.MAX_SAFE_INTEGER,o=Array.isArray(this.data)?this.data.length:0,a=this.minimal?"":n`
            <span slot="header">${this.label?e(this.label,this.required,!1):""}</span>
            <div id="header-description" slot="header-description">
                <div id="errors">
                    ${!this.errors?"":n`<or-icon icon="alert"></or-icon><span>${this.errors}</span>`}
                </div>
                <div id="header-buttons"><or-mwc-input .type="${f.BUTTON}" outlined label="json" icon="pencil" @or-mwc-input-changed="${e=>this._showJson(e)}"></or-mwc-input></div>
            </div>
        `,s=n`
            ${a}
            <div id="content-wrapper" slot="content">
                <div id="content" @dragover="${e=>this._onDragOver(e)}">
                    
                    ${!Array.isArray(this.data)?"":this.data.map((e,t)=>{let r=i.compose(this.path,""+t),o={renderers:this.renderers,uischema:c("#"),schema:this.resolvedSchema,path:r};return this.getArrayItemWrapper(h(this.state,o)||n``,t)})}

                </div>
                ${this.errors?"":n`
                    <div id="footer">
                        <or-mwc-input .disabled="${o&&o>=r}" .type="${f.BUTTON}" label="addItem" icon="plus" @or-mwc-input-changed="${()=>this.doAddItem()}"></or-mwc-input>
                    </div>
                `}
            </div>
        `;return this.minimal?n`<div>${s}</div>`:n`<or-collapsible-panel>${s}</or-collapsible-panel>`}getArrayItemWrapper(e,t){return n`
            <div class="item-wrapper" data-index="${t}">
                <div class="drag-container">
                    <button draggable="true" @dragstart="${e=>this._onDragStart(e)}" @dragend="${e=>this._onDragEnd(e)}" class="draggable button-clear"><or-icon icon="menu"></or-icon></input>
                </div>
                ${E(e,()=>this.removeItem(t))}
            </div>
        `}_onDragStart(e){let t=e.currentTarget.parentElement.parentElement;t.classList.add("dragging");let r=t.lastElementChild;e.dataTransfer.setDragImage(r,r.getBoundingClientRect().width/2-50,0)}_onDragEnd(e){let t=[...this.shadowRoot.querySelectorAll(".item-wrapper")],r=e.currentTarget.parentElement.parentElement;r.classList.remove("dragging");let i=Number(r.getAttribute("data-index")),o=Math.max(0,(null!==r.getAttribute("data-after-index")?Number(r.getAttribute("data-after-index")):t.length)-1);t.forEach(e=>e.classList.remove("indicator-before","indicator-after")),i!==o&&this.moveItem(i,o)}_onDragOver(e){let t=this.shadowRoot.querySelector(".dragging");if(!t)return;e.preventDefault();let r=[...this.shadowRoot.querySelectorAll(".item-wrapper:not(.dragging)")],i=r.reduce((t,r)=>{let i=r.getBoundingClientRect(),o=e.clientY-i.top-i.height/2;return o<0&&o>t.offset?{offset:o,element:r}:t},{offset:-1/0,element:null}).element;if(r.forEach(e=>e.classList.remove("indicator-before","indicator-after")),null===i)r[r.length-1].classList.add("indicator-after"),t.removeAttribute("data-after-index");else{i.classList.add("indicator-before");let e=i.getAttribute("data-index");t.setAttribute("data-after-index",e)}}_showJson(e){e.stopPropagation(),g(this.title||this.schema.title||"",this.data,e=>{this.handleChange(this.path||"",e)})}doAddItem(){this.resolvedSchema&&(this.itemInfos?this.showAddDialog():this.addItem(t(this.resolvedSchema,this.rootSchema)))}showAddDialog(){let t,r=this.itemInfos.map((t,r)=>{let i=t.title?e(t.title,!1,!0):"";return{text:i,value:i,data:t}}),i=b(new v().setContent(n`
                <div class="col">
                    <form id="mdc-dialog-form-add" class="row">
                        <div id="type-list" class="col">
                            <or-mwc-list @or-mwc-list-changed="${e=>{var r;1===e.detail.length&&(t=r=e.detail[0].data,i.shadowRoot.getElementById("parameter-desc").innerHTML=r.description||"",i.shadowRoot.getElementById("add-btn").disabled=!1)}}" .listItems="${r.sort((e,t)=>e.text.localeCompare(t.text))}" id="parameter-list"></or-mwc-list>
                        </div>
                        <div id="parameter-desc" class="col"></div>
                    </form>
                </div>
            `).setStyles(w).setHeading((this.label?e(this.label,this.required,!1)+" - ":"")+u.t("addItem")).setActions([{actionName:"cancel",content:"cancel"},{default:!0,actionName:"add",action:()=>{if(t){let e=t.defaultValueCreator();this.addItem(e)}},content:n`<or-mwc-input id="add-btn" .type="${f.BUTTON}" disabled label="add"></or-mwc-input>`}]).setDismissAction(null))}};__decorate([m()],ControlArrayElement.prototype,"minimal",void 0),ControlArrayElement=__decorate([l("or-json-forms-array-control")],ControlArrayElement);export{ControlArrayElement};