var __decorate=this&&this.__decorate||function(e,t,r,o){var i,a=arguments.length,s=a<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var n=e.length-1;n>=0;n--)(i=e[n])&&(s=(a<3?i(s):a>3?i(t,r,s):i(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 o,Resolve as i,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 f}from"../util";import{InputType as g}from"@openremote/or-mwc-components/or-mwc-input";import{i18next as u}from"@openremote/or-translate";import{OrMwcDialog as v,showDialog as w}from"@openremote/or-mwc-components/or-mwc-dialog";import"@openremote/or-mwc-components/or-mwc-list";import{addItemOrParameterDialogStyle as b,baseStyle as y,panelStyle as A}from"../styles";import{DefaultColor4 as x,DefaultColor5 as I}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(I)});
        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(x)});
    }

    .item-wrapper.indicator-before {
        border-top-width: 3px;
        border-top-style: solid;
        border-top-color: var(--or-app-color4, ${d(x)});
    }
    
    .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 ${static get styles(){return[y,A,style]}shouldUpdate(e){if(e.has("schema")&&(this.itemInfos=void 0,this.resolvedSchema=i.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 o,i;return o=1,i=r.splice(e,o)[0],o=0,r.splice(t,o,i),r}))}}return super.shouldUpdate(e)}render(){var t;let r=null!=(t=this.schema.maxItems)?t:Number.MAX_SAFE_INTEGER,i=Array.isArray(this.data)?this.data.length:0,a=this.minimal?"":n`
            <div slot="header">
                <span>${this.label?e(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-mwc-input .type="${g.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=o.compose(this.path,""+t),i={renderers:this.renderers,uischema:c("#"),schema:this.resolvedSchema,path:r};return this.getArrayItemWrapper(h(this.state,i)||n``,t)})}

                </div>
                ${this.errors?"":n`
                    <div id="footer">
                        <or-mwc-input .disabled="${i&&i>=r}" .type="${g.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 o=Number(r.getAttribute("data-index")),i=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")),o!==i&&this.moveItem(o,i)}_onDragOver(e){let t=this.shadowRoot.querySelector(".dragging");if(!t)return;e.preventDefault();let r=[...this.shadowRoot.querySelectorAll(".item-wrapper:not(.dragging)")],o=r.reduce((t,r)=>{let o=r.getBoundingClientRect(),i=e.clientY-o.top-o.height/2;return i<0&&i>t.offset?{offset:i,element:r}:t},{offset:-1/0,element:null}).element;if(r.forEach(e=>e.classList.remove("indicator-before","indicator-after")),null===o)r[r.length-1].classList.add("indicator-after"),t.removeAttribute("data-after-index");else{o.classList.add("indicator-before");let e=o.getAttribute("data-index");t.setAttribute("data-after-index",e)}}_showJson(e){e.stopPropagation(),f(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 o=t.title?e(t.title,!1,!0):"";return{text:o,value:o,data:t}}),o=w(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,o.shadowRoot.getElementById("parameter-desc").innerHTML=r.description||"",o.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(b).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="${g.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};