import*as Platform from"../platform/platform.js";import{Events}from"./DataGrid.js";import{ViewportDataGrid,ViewportDataGridNode}from"./ViewportDataGrid.js";export class SortableDataGrid extends ViewportDataGrid{constructor(t){super(t),this._sortingFunction=SortableDataGrid.TrivialComparator,this.setRootNode(new SortableDataGridNode)}static TrivialComparator(t,r){return 0}static NumericComparator(t,r,e){const o=r.data[t],i=e.data[t],n=Number(o instanceof Node?o.textContent:o),a=Number(i instanceof Node?i.textContent:i);return n<a?-1:n>a?1:0}static StringComparator(t,r,e){const o=r.data[t],i=e.data[t],n=o instanceof Node?o.textContent:String(o),a=i instanceof Node?i.textContent:String(i);return n&&a?n<a?-1:n>a?1:0:0}static Comparator(t,r,e,o){return r?t(o,e):t(e,o)}static create(t,r,e){const o=t.length;if(!o)return null;const i=[];for(let l=0;l<t.length;++l){const r=String(l);i.push({id:r,title:t[l],sortable:!0})}const n=[];for(let l=0;l<r.length/o;++l){const e={};for(let n=0;n<t.length;++n)e[n]=r[o*l+n];const i=new SortableDataGridNode(e);i.selectable=!1,n.push(i)}const a=new SortableDataGrid({displayName:e,columns:i}),s=n.length,d=a.rootNode();for(let l=0;l<s;++l)d.appendChild(n[l]);return a.addEventListener(Events.SortingChanged,(function(){const t=a.rootNode().children,r=a.sortColumnId();if(!r)return;let e=!0;for(let i=0;i<t.length;i++){const o=t[i].data[r];if(isNaN(o instanceof Node?o.textContent:o)){e=!1;break}}const o=e?SortableDataGrid.NumericComparator:SortableDataGrid.StringComparator;a.sortNodes(o.bind(null,r),!a.isSortOrderAscending())})),a}insertChild(t){this.rootNode().insertChildOrdered(t)}sortNodes(t,r){this._sortingFunction=SortableDataGrid.Comparator.bind(null,t,r),this.rootNode().recalculateSiblings(0),this.rootNode()._sortChildren(),this.scheduleUpdateStructure()}}export class SortableDataGridNode extends ViewportDataGridNode{constructor(t,r){super(t,r)}insertChildOrdered(t){const r=this.dataGrid;r&&this.insertChild(t,Platform.ArrayUtilities.upperBound(this.children,t,r._sortingFunction))}_sortChildren(){const t=this.dataGrid;if(t){this.children.sort(t._sortingFunction);for(let t=0;t<this.children.length;++t){this.children[t].recalculateSiblings(t)}for(let t=0;t<this.children.length;++t){this.children[t]._sortChildren()}}}}