var __decorate=this&&this.__decorate||function(t,e,r,o){var a,i=arguments.length,s=i<3?e:null===o?o=Object.getOwnPropertyDescriptor(e,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,r,o);else for(var n=t.length-1;n>=0;n--)(a=t[n])&&(s=(i<3?a(s):i>3?a(e,r,s):a(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s};import{computeLabel as t,createDefaultValue as e,mapDispatchToArrayControlProps as r,Paths as o,Resolve as a,update as i}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 h,getTemplateFromProps as p,showJsonEditor as f}from"../util";import{i18next as v}from"@openremote/or-translate";import{OrMwcDialog as g,showDialog as u}from"@openremote/or-mwc-components/or-mwc-dialog";import"@openremote/or-mwc-components/or-mwc-list";import{addItemOrParameterDialogStyle as b,baseStyle as w,panelStyle as y}from"../styles";import"@openremote/or-vaadin-components/or-vaadin-button";import{DefaultColor4 as A,DefaultColor5 as x}from"@openremote/core";import{ControlBaseElement as I}from"./control-base-element";import{getTemplateWrapper as $}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(A)});
    }

    .item-wrapper.indicator-before {
        border-top-width: 3px;
        border-top-style: solid;
        border-top-color: var(--or-app-color4, ${d(A)});
    }
    
    .drag-container > button {
        cursor: grab;
    }

    #content-wrapper {
        overflow: auto;
    }

    [slot="header"] {
        display: flex;
        min-width: 0; /* Allows slotted element to shrink */
        & span {
            align-content: center;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            word-break: break-all;
        }
    }
`,ControlArrayElement=class extends I{static get styles(){return[w,y,style]}shouldUpdate(t){if(t.has("schema")&&(this.itemInfos=void 0,this.resolvedSchema=a.schema(this.schema,"items",this.rootSchema),Array.isArray(this.resolvedSchema.anyOf)?this.itemInfos=h(this.resolvedSchema.anyOf,this.rootSchema):Array.isArray(this.resolvedSchema.oneOf)&&(this.itemInfos=h(this.resolvedSchema.oneOf,this.rootSchema))),t.has("state")){let t=r(this.state.dispatch);this.addItem=e=>t.addItem(this.path,e)(),this.removeItem=e=>{t.removeItems(this.path,[e])()},this.moveItem=(t,e)=>{this.state.dispatch(i(this.path,r=>{let o,a;return o=1,a=r.splice(t,o)[0],o=0,r.splice(e,o,a),r}))}}return super.shouldUpdate(t)}render(){var e;let r=null!=(e=this.schema.maxItems)?e:Number.MAX_SAFE_INTEGER,a=Array.isArray(this.data)?this.data.length:0,i=this.minimal?"":n`
            <div slot="header">
                <span>${this.label?t(this.label,this.required,!1):""}</span>
            </div>
            <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-vaadin-button @click=${t=>this._showJson(t)}>
                        <or-icon slot="prefix" icon="pencil"></or-icon>
                        <or-translate value="JSON"></or-translate>
                    </or-vaadin-button>
                </div>
            </div>
        `,s=n`
            ${i}
            <div id="content-wrapper" slot="content">
                <div id="content" @dragover="${t=>this._onDragOver(t)}">
                    
                    ${!Array.isArray(this.data)?"":this.data.map((t,e)=>{let r=o.compose(this.path,""+e),a={renderers:this.renderers,uischema:c("#"),schema:this.resolvedSchema,path:r};return this.getArrayItemWrapper(p(this.state,a)||n``,e)})}

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