var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "../../core/AtomBinder", "../../core/AtomEnumerator", "../../core/AtomList", "../../core/XNode", "../../web/core/AtomUI", "./AtomControl"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AtomItemsControl = void 0;
    var AtomBinder_1 = require("../../core/AtomBinder");
    var AtomEnumerator_1 = require("../../core/AtomEnumerator");
    require("../../core/AtomList");
    var XNode_1 = require("../../core/XNode");
    var AtomUI_1 = require("../../web/core/AtomUI");
    var AtomControl_1 = require("./AtomControl");
    var AtomItemsControl = /** @class */ (function (_super) {
        __extends(AtomItemsControl, _super);
        function AtomItemsControl() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.mValue = undefined;
            // private mFilteredItems: any[] = [];
            // private mSelectedItem: any = undefined;
            _this.mFilter = undefined;
            _this.mFirstChild = null;
            _this.mLastChild = null;
            _this.mScrollerSetup = false;
            _this.mScopes = null;
            _this.mItemsDisposable = null;
            _this.isUpdating = false;
            return _this;
        }
        Object.defineProperty(AtomItemsControl.prototype, "itemsPresenter", {
            get: function () {
                return this.mItemsPresenter || (this.mItemsPresenter = this.element);
            },
            set: function (v) {
                this.mItemsPresenter = v;
                AtomBinder_1.AtomBinder.refreshValue(this, "itemsPresenter");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomItemsControl.prototype, "value", {
            get: function () {
                var _this = this;
                if (this.allowMultipleSelection) {
                    var items = this.mSelectedItems;
                    if (items.length === 0) {
                        if (this.mValue !== undefined) {
                            return this.mValue;
                        }
                        return null;
                    }
                    items = items.map(function (m) { return m[_this.valuePath]; });
                    if (this.valueSeparator) {
                        items = items.join(this.valueSeparator);
                    }
                    return items;
                }
                var s = this.selectedItem;
                if (!s) {
                    if (this.mValue !== undefined) {
                        return this.mValue;
                    }
                    return null;
                }
                if (this.valuePath) {
                    s = s[this.valuePath];
                }
                return s;
            },
            set: function (v) {
                this.mValue = v;
                var dataItems = this.items;
                if (!dataItems) {
                    return;
                }
                var sItems = this.selectedItems;
                if (v === undefined || v === null) {
                    // reset...
                    AtomBinder_1.AtomBinder.clear(sItems);
                    return;
                }
                if (this.allowMultipleSelection && this.valueSeparator) {
                    if (typeof v !== "string") {
                        v = "" + v;
                    }
                    v = v.split(this.valueSeparator);
                }
                else {
                    v = [v];
                }
                // const items = AtomArray.intersect(dataItems, this._valuePath, v);
                sItems.length = 0;
                var vp = this.valuePath;
                for (var _i = 0, v_1 = v; _i < v_1.length; _i++) {
                    var item = v_1[_i];
                    // tslint:disable-next-line:triple-equals
                    var dataItem = dataItems.find(function (i) { return i[vp] == v; });
                    if (dataItem) {
                        sItems.push(dataItem);
                    }
                }
                // this.updateSelectionBindings();
                AtomBinder_1.AtomBinder.refreshItems(sItems);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomItemsControl.prototype, "items", {
            get: function () {
                return this.mItems;
            },
            set: function (v) {
                var _this = this;
                if (this.mItemsDisposable) {
                    this.mItemsDisposable.dispose();
                    this.mItemsDisposable = null;
                }
                this.mItems = v;
                // this.mFilteredItems = null;
                if (v != null) {
                    this.mItemsDisposable = this.registerDisposable(AtomBinder_1.AtomBinder.add_CollectionChanged(v, function (target, key, index, item) {
                        _this.onCollectionChangedInternal(key, index, item);
                    }));
                    // this.onCollectionChangedInternal("refresh", -1, null);
                }
                AtomBinder_1.AtomBinder.refreshValue(this, "items");
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomItemsControl.prototype, "selectedItem", {
            get: function () {
                if (this.selectedItems.length > 0) {
                    return this.selectedItems[0];
                }
                return null;
            },
            set: function (value) {
                if (value !== undefined && value !== null) {
                    this.mSelectedItems.length = 1;
                    this.mSelectedItems[0] = value;
                }
                else {
                    this.mSelectedItems.length = 0;
                }
                AtomBinder_1.AtomBinder.refreshItems(this.mSelectedItems);
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomItemsControl.prototype, "selectedItems", {
            get: function () {
                return this.mSelectedItems || (this.selectedItems = []);
            },
            set: function (v) {
                var _this = this;
                if (this.mSelectedItemsWatcher) {
                    this.mSelectedItemsWatcher.dispose();
                    this.mSelectedItemsWatcher = null;
                }
                this.mSelectedItems = v;
                if (v) {
                    this.mSelectedItemsWatcher = this.registerDisposable(AtomBinder_1.AtomBinder.add_CollectionChanged(v, function (t, k, i, item) {
                        _this.onSelectedItemsChanged(k, i, item);
                    }));
                }
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomItemsControl.prototype, "selectedIndex", {
            get: function () {
                if (!this.mItems) {
                    return -1;
                }
                var item = this.selectedItem;
                return this.mItems.indexOf(item);
            },
            set: function (n) {
                if (!this.mItems) {
                    return;
                }
                if (n <= -1 || n >= this.mItems.length) {
                    this.selectedItem = null;
                    return;
                }
                this.selectedItem = this.mItems[n];
            },
            enumerable: false,
            configurable: true
        });
        AtomItemsControl.prototype.hasProperty = function (name) {
            // tslint:disable-next-line: max-line-length
            if (/^(items|itemsPresenter|value|valuePath|valueSeparator|label|labelPath|selectedItems|selectedItem|selectedIndex|uiVirtualize|viewModel|localViewModel|data)$/.test(name)) {
                return true;
            }
            return _super.prototype.hasProperty.call(this, name);
        };
        AtomItemsControl.prototype.dispose = function (e) {
            this.items = null;
            this.selectedItems = null;
            // this.mFilteredItems = null;
            _super.prototype.dispose.call(this, e);
        };
        AtomItemsControl.prototype.onPropertyChanged = function (name) {
            switch (name) {
                case "itemsPresenter":
                case "itemTemplate":
                case "labelPath":
                case "valuePath":
                case "items":
                case "filter":
                case "sort":
                    if (this.mItems) {
                        this.invalidateItems();
                    }
                    // this.runAfterInit(() => {
                    //     if (this.mItems) {
                    //         this.onCollectionChangedInternal("refresh", -1, null);
                    //     }
                    // });
                    break;
            }
        };
        Object.defineProperty(AtomItemsControl.prototype, "selectAll", {
            set: function (v) {
                if (v === undefined || v === null) {
                    return;
                }
                this.mSelectedItems.length = 0;
                var items = this.mItems;
                if (v && items) {
                    for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
                        var itm = items_1[_i];
                        this.mSelectedItems.push(itm);
                    }
                }
                this.mSelectAll = true;
                AtomBinder_1.AtomBinder.refreshItems(this.mSelectedItems);
            },
            enumerable: false,
            configurable: true
        });
        AtomItemsControl.prototype.resetVirtualContainer = function () {
            var ip = this.itemsPresenter;
            if (ip) {
                this.disposeChildren(ip);
            }
            this.mFirstChild = null;
            this.mLastChild = null;
            this.mScrollerSetup = false;
            this.mScopes = null;
            this.unbindEvent(this.mVirtualContainer, "scroll");
        };
        AtomItemsControl.prototype.postVirtualCollectionChanged = function () {
            var _this = this;
            this.app.callLater(function () {
                _this.onVirtualCollectionChanged();
            });
        };
        AtomItemsControl.prototype.onVirtualCollectionChanged = function () {
            var _this = this;
            var ip = this.itemsPresenter;
            var items = this.items;
            if (!items.length) {
                this.resetVirtualContainer();
                return;
            }
            this.validateScroller();
            var fc = this.mFirstChild;
            var lc = this.mLastChild;
            var vc = this.mVirtualContainer;
            var vcHeight = AtomUI_1.AtomUI.innerHeight(vc);
            var vcScrollHeight = vc.scrollHeight;
            if (isNaN(vcHeight) || vcHeight <= 0 || vcScrollHeight <= 0) {
                setTimeout(function () {
                    _this.onVirtualCollectionChanged();
                }, 1000);
                return;
            }
            var vcWidth = AtomUI_1.AtomUI.innerWidth(vc);
            var avgHeight = this.mAvgHeight;
            var avgWidth = this.mAvgWidth;
            var itemsHeight = vc.scrollHeight - AtomUI_1.AtomUI.outerHeight(fc) - AtomUI_1.AtomUI.outerHeight(lc);
            var itemsWidth = AtomUI_1.AtomUI.innerWidth(ip);
            var element = this.element;
            var ce;
            var ae = new AtomEnumerator_1.default(items);
            if (this.mTraining) {
                if (vcHeight >= itemsHeight) {
                    // lets add item...
                    ce = lc.previousElementSibling;
                    if (ce !== fc) {
                        var data = ce.atomControl.data;
                        while (ae.next()) {
                            if (ae.current === data) {
                                break;
                            }
                        }
                    }
                    if (ae.next()) {
                        var data = ae.current;
                        var elementChild = this.createChild(null, data);
                        ip.insertBefore(elementChild.element, lc);
                        this.postVirtualCollectionChanged();
                    }
                }
                else {
                    // calculate avg height
                    var totalVisibleItems = 0;
                    ce = fc.nextElementSibling;
                    var allHeight = 0;
                    var allWidth = 0;
                    while (ce !== lc) {
                        totalVisibleItems++;
                        allHeight += AtomUI_1.AtomUI.outerHeight(ce);
                        allWidth += AtomUI_1.AtomUI.outerWidth(ce);
                        ce = ce.nextElementSibling;
                    }
                    avgHeight = allHeight / totalVisibleItems;
                    avgWidth = allWidth / totalVisibleItems;
                    totalVisibleItems--;
                    this.mAvgHeight = avgHeight;
                    this.mAvgWidth = avgWidth;
                    var columns = Math.floor(vcWidth / avgWidth);
                    var allRows = Math.ceil(items.length / columns);
                    var visibleRows = Math.ceil(totalVisibleItems / columns);
                    // tslint:disable-next-line:no-console
                    console.log({
                        avgWidth: avgWidth,
                        avgHeight: avgHeight,
                        totalVisibleItems: totalVisibleItems,
                        allRows: allRows,
                        columns: columns
                    });
                    this.mAllRows = allRows;
                    this.mColumns = columns;
                    this.mVisibleRows = visibleRows;
                    this.mVisibleHeight = visibleRows * avgHeight;
                    // set height of last child... to increase padding
                    lc.style.height = ((allRows - visibleRows + 1) * avgHeight) + "px";
                    this.mTraining = false;
                    this.mReady = true;
                    this.postVirtualCollectionChanged();
                }
                return;
            }
            var self = this;
            this.lastScrollTop = vc.scrollTop;
            if (this.mIsChanging) {
                // setTimeout(function () {
                //    self.onVirtualCollectionChanged();
                // }, 100);
                return;
            }
            this.mIsChanging = true;
            var block = Math.floor(this.mVisibleHeight / avgHeight);
            var itemsInBlock = this.mVisibleRows * this.mColumns;
            // lets simply recreate the view... if we are out of the scroll bounds...
            var index = Math.floor(vc.scrollTop / this.mVisibleHeight);
            var itemIndex = index * itemsInBlock;
            // console.log("First block index is " + index + " item index is " + index * itemsInBlock);
            if (itemIndex >= items.length) {
                this.mIsChanging = false;
                return;
            }
            var lastIndex = Math.min((Math.max(index, 0) + 3) * itemsInBlock - 1, items.length - 1);
            var firstIndex = Math.max(0, (index) * itemsInBlock);
            ce = fc.nextElementSibling;
            var firstItem = fc.nextElementSibling;
            var lastItem = lc.previousElementSibling;
            if (firstItem !== lastItem) {
                var firstVisibleIndex = items.indexOf(firstItem.atomControl.data);
                var lastVisibleIndex = items.indexOf(lastItem.atomControl.data);
                // tslint:disable-next-line:no-console
                console.log({
                    firstVisibleIndex: firstVisibleIndex,
                    firstIndex: firstIndex,
                    lastVisibleIndex: lastVisibleIndex,
                    lastIndex: lastIndex
                });
                if (firstIndex >= firstVisibleIndex && lastIndex <= lastVisibleIndex) {
                    // tslint:disable-next-line:no-console
                    console.log("All items are visible...");
                    this.mIsChanging = false;
                    return;
                }
            }
            var remove = [];
            var cache = {};
            while (ce !== lc) {
                var c = ce;
                ce = ce.nextElementSibling;
                var s = items.indexOf(c.atomControl.data);
                cache[s] = c;
                remove.push(c);
            }
            this.app.dispatcher.pause();
            ae = new AtomEnumerator_1.default(items);
            for (var i = 0; i < firstIndex; i++) {
                ae.next();
            }
            var after = fc;
            var last = null;
            var add = [];
            for (var i = firstIndex; i <= lastIndex; i++) {
                if (!ae.next()) {
                    break;
                }
                var index2 = ae.currentIndex;
                var data = ae.current;
                var elementChild = cache[index2];
                if (elementChild && element.atomControl.data === data) {
                    cache[index2] = null;
                }
                else {
                    elementChild = this.createChild(null, data).element;
                }
                elementChild.before = after;
                add.push(elementChild);
                after = elementChild;
                last = index2;
            }
            var h = (this.mAllRows - block * 3) * avgHeight - index * this.mVisibleHeight;
            // tslint:disable-next-line:no-console
            console.log("last child height = " + h);
            this.app.callLater(function () {
                var oldHeight = AtomUI_1.AtomUI.outerHeight(fc);
                var newHeight = index * _this.mVisibleHeight;
                var diff = newHeight - oldHeight;
                var oldScrollTop = vc.scrollTop;
                var a = new AtomEnumerator_1.default(add);
                while (a.next()) {
                    var ec = a.current;
                    ip.insertBefore(ec, ec.before.nextElementSibling);
                    ec.before = null;
                }
                fc.style.height = newHeight + "px";
                for (var _i = 0, remove_1 = remove; _i < remove_1.length; _i++) {
                    var iterator = remove_1[_i];
                    if (!iterator.before) {
                        iterator.atomControl.dispose();
                    }
                    iterator.remove();
                }
                // const a = new AtomEnumerator(remove);
                // while (a.next()) {
                //     const ec = a.current();
                //     if (!ec.before) {
                //         ec.atomControl.dispose();
                //     }
                //     ec.remove();
                // }
                // vc.scrollTop = oldScrollTop - diff;
                lc.style.height = h + "px";
                // tslint:disable-next-line:no-console
                console.log("Old: " + oldScrollTop + " Diff: " + diff + " Old Height: " + oldHeight + " Height: " + newHeight);
                _this.mIsChanging = false;
            });
            this.app.dispatcher.start();
            AtomBinder_1.AtomBinder.refreshValue(this, "childAtomControls");
        };
        AtomItemsControl.prototype.isSelected = function (item) {
            var selectedItem = null;
            for (var _i = 0, _a = this.mSelectedItems; _i < _a.length; _i++) {
                var iterator = _a[_i];
                selectedItem = iterator;
                if (selectedItem === item) {
                    return true;
                }
            }
            return false;
        };
        AtomItemsControl.prototype.bringIntoView = function (data) {
            var _this = this;
            this.app.callLater(function () {
                var en = new AtomUI_1.ChildEnumerator(_this.itemsPresenter || _this.element);
                while (en.next()) {
                    var item = en.current;
                    var dataItem = item.atomControl ? item.atomControl.data : item;
                    if (dataItem === data) {
                        item.scrollIntoView();
                        return;
                    }
                }
            });
        };
        AtomItemsControl.prototype.bringSelectionIntoView = function () {
            // do not scroll for first auto select
            // if (this.mAllowSelectFirst && this.get_selectedIndex() === 0) {
            //     return;
            // }
            var _this = this;
            if (this.uiVirtualize) {
                var index = this.selectedIndex;
                if (!this.mReady) {
                    setTimeout(function () {
                        _this.bringSelectionIntoView();
                    }, 1000);
                    return;
                }
                var avgHeight = this.mAvgHeight;
                var vcHeight = AtomUI_1.AtomUI.innerHeight(this.mVirtualContainer);
                var block = Math.ceil(vcHeight / avgHeight);
                var itemsInBlock = block * this.mColumns;
                var scrollTop = Math.floor(index / itemsInBlock);
                AtomUI_1.AtomUI.scrollTop(this.mVirtualContainer, scrollTop * vcHeight);
                return;
            }
            var en = new AtomUI_1.ChildEnumerator(this.itemsPresenter || this.element);
            var _loop_1 = function () {
                var item = en.current;
                var dataItem = item.atomControl ? item.atomControl.data : item;
                if (this_1.isSelected(dataItem)) {
                    setTimeout(function () {
                        item.scrollIntoView();
                    }, 1000);
                    return { value: void 0 };
                }
            };
            var this_1 = this;
            while (en.next()) {
                var state_1 = _loop_1();
                if (typeof state_1 === "object")
                    return state_1.value;
            }
        };
        AtomItemsControl.prototype.updateSelectionBindings = function () {
            this.version = this.version + 1;
            if (this.mSelectedItems && this.mSelectedItems.length) {
                this.mValue = undefined;
            }
            AtomBinder_1.AtomBinder.refreshValue(this, "value");
            AtomBinder_1.AtomBinder.refreshValue(this, "selectedItem");
            AtomBinder_1.AtomBinder.refreshValue(this, "selectedItems");
            AtomBinder_1.AtomBinder.refreshValue(this, "selectedIndex");
            if (!this.mSelectedItems.length) {
                if (this.mSelectAll === true) {
                    this.mSelectAll = false;
                    AtomBinder_1.AtomBinder.refreshValue(this, "selectAll");
                }
            }
        };
        AtomItemsControl.prototype.onSelectedItemsChanged = function (type, index, item) {
            if (!this.mOnUIChanged) {
                // this.updateChildSelections(type, index, item);
                if (this.autoScrollToSelection) {
                    this.bringSelectionIntoView();
                }
            }
            this.updateSelectionBindings();
            // AtomControl.updateUI();
            // this.invokePost();
        };
        AtomItemsControl.prototype.hasItems = function () {
            return this.mItems !== undefined && this.mItems !== null;
        };
        AtomItemsControl.prototype.invalidateItems = function () {
            var _this = this;
            if (this.pendingInits || this.isUpdating) {
                setTimeout(function () {
                    _this.invalidateItems();
                }, 5);
                return;
            }
            if (this.itemsInvalidated) {
                clearTimeout(this.itemsInvalidated);
                this.itemsInvalidated = 0;
            }
            this.itemsInvalidated = setTimeout(function () {
                _this.itemsInvalidated = 0;
                _this.onCollectionChangedInternal("refresh", -1, null);
            }, 5);
            // this.registerDisposable({
            //     dispose: () => {
            //         if (this.itemsInvalidated) {
            //             clearTimeout(this.itemsInvalidated);
            //         }
            //     }
            // });
        };
        AtomItemsControl.prototype.onCollectionChanged = function (key, index, item) {
            if (!this.mItems) {
                return;
            }
            if (!this.itemTemplate) {
                return;
            }
            if (!this.itemsPresenter) {
                this.itemsPresenter = this.element;
            }
            this.version = this.version + 1;
            if (/reset|refresh/i.test(key)) {
                this.resetVirtualContainer();
            }
            if (/remove/gi.test(key)) {
                // tslint:disable-next-line:no-shadowed-variable
                var ip_1 = this.itemsPresenter || this.element;
                var en = new AtomUI_1.ChildEnumerator(ip_1);
                while (en.next()) {
                    var ce = en.current;
                    // tslint:disable-next-line:no-shadowed-variable
                    var c = ce;
                    if (c.atomControl && c.atomControl.data === item) {
                        c.atomControl.dispose();
                        ce.remove();
                        break;
                    }
                }
                // AtomControl.updateUI();
                return;
            }
            if (this.uiVirtualize) {
                this.onVirtualCollectionChanged();
                return;
            }
            // AtomUIComponent
            var parentScope = undefined;
            // const parentScope = this.get_scope();
            // const et = this.getTemplate("itemTemplate");
            // if (et) {
            //     et = AtomUI.getAtomType(et);
            //     if (et) {
            //         this._childItemType = et;
            //     }
            // }
            var items = this.mFilter ? this.mItems.filter(this.mFilter) : this.mItems;
            var s = this.sort;
            if (s) {
                if (typeof s === "string") {
                    var sp_1 = s;
                    s = function (l, r) {
                        var lv = (l[sp_1] || "").toString();
                        var rv = (r[sp_1] || "").toString();
                        return lv.toLowerCase().localeCompare(rv.toLowerCase());
                    };
                }
                items = items.sort(s);
            }
            if (/add/gi.test(key)) {
                // WebAtoms.dispatcher.pause();
                // for (const aeItem of this.mItems) {
                //     for (const ceItem of AtomUI.childEnumerator(this.itemsPresenter)) {
                //         const d: any = ceItem;
                //         if (aeItem.currentIndex() === index) {
                //             const ctl: any = this.createChildElement(parentScope, this.itemsPresenter, item, aeItem, d);
                //             this.applyItemStyle(ctl, item, aeItem.isFirst(), aeItem.isLast());
                //             break;
                //         }
                //         if (aeItem.isLast()) {
                // tslint:disable-next-line:max-line-length
                //             const ctl: any = this.createChildElement(parentScope, this.itemsPresenter, item, aeItem, null);
                //             this.applyItemStyle(ctl, item, aeItem.isFirst(), aeItem.isLast());
                //             break;
                //         }
                //     }
                // }
                // WebAtoms.dispatcher.start();
                // AtomControl.updateUI();
                var lastItem = items[index];
                var last = null;
                var cIndex = 0;
                var en = new AtomUI_1.ChildEnumerator(this.itemsPresenter);
                while (en.next()) {
                    if (cIndex === index) {
                        last = en.current;
                        break;
                    }
                    cIndex++;
                }
                var df2 = document.createDocumentFragment();
                this.createChild(df2, lastItem);
                if (last) {
                    this.itemsPresenter.insertBefore(df2, last);
                }
                else {
                    this.itemsPresenter.appendChild(df2);
                }
                return;
            }
            var element = this.itemsPresenter;
            // const dataItems = this.get_dataItems();
            // AtomControl.disposeChildren(element);
            this.disposeChildren(this.itemsPresenter);
            // WebAtoms.dispatcher.pause();
            // const items = this.get_dataItems(true);
            var added = [];
            // this.getTemplate("itemTemplate");
            // tslint:disable-next-line:no-console
            // console.log("Started");
            // const df = document.createDocumentFragment();
            var ip = this.itemsPresenter || this.element;
            for (var _i = 0, items_2 = items; _i < items_2.length; _i++) {
                var mItem = items_2[_i];
                var data = mItem;
                // const elementChild = this.createChildElement(parentScope, element, data, mItem, null);
                // added.push(elementChild);
                // this.applyItemStyle(elementChild, data, mItem.isFirst(), mItem.isLast());
                var ac = this.createChild(null, data);
                ip.appendChild(ac.element);
            }
            // (this.element as HTMLElement).appendChild(df);
            // tslint:disable-next-line:no-console
            // console.log("Ended");
            // const self = this;
            // WebAtoms.dispatcher.callLater(() => {
            //     const dirty = [];
            //     for (const elementItem of AtomUI.childEnumerator(element)) {
            //         const ct = elementItem;
            //         const func = added.filter((fx) => ct === fx);
            //         if (func.pop() !== ct) {
            //             dirty.push(ct);
            //         }
            //     }
            //     for (const dirtyItem of dirty) {
            //         const drt = dirtyItem;
            //         if (drt.atomControl) {
            //             drt.atomControl.dispose();
            //         }
            //         AtomUI.remove(item);
            //     }
            //     });
            // WebAtoms.dispatcher.start();
            // AtomBinder.refreshValue(this, "childAtomControls");
        };
        AtomItemsControl.prototype.preCreate = function () {
            this.mAllowSelectFirst = false;
            this.allowMultipleSelection = false;
            this.valuePath = "value";
            this.labelPath = "label";
            this.version = 1;
            this.autoScrollToSelection = false;
            this.sort = null;
            this.valueSeparator = ", ";
            this.uiVirtualize = false;
            this.mSelectAll = false;
            this.mItems = null;
            this.selectedItems = [];
            this.itemTemplate = AtomItemsControlItemTemplate;
            _super.prototype.preCreate.call(this);
        };
        AtomItemsControl.prototype.onCollectionChangedInternal = function (key, index, item) {
            var _this = this;
            // Atom.refresh(this, "allValues");
            // AtomBinder.refreshValue(this, "allValues");
            var value = this.value;
            try {
                this.isUpdating = true;
                this.onCollectionChanged(key, index, item);
                if (value) {
                    if (!(value || this.mAllowSelectFirst)) {
                        AtomBinder_1.AtomBinder.clear(this.mSelectedItems);
                    }
                }
                if (value != null) {
                    this.value = value;
                    if (this.selectedIndex !== -1) {
                        return;
                    }
                    else {
                        this.mValue = undefined;
                    }
                }
            }
            finally {
                this.app.callLater(function () {
                    _this.isUpdating = false;
                });
            }
            // this.selectDefault();
        };
        Object.defineProperty(AtomItemsControl.prototype, "allowSelectFirst", {
            set: function (b) {
                b = b ? b !== "false" : b;
                this.mAllowSelectFirst = b;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(AtomItemsControl.prototype, "filter", {
            set: function (f) {
                if (f === this.mFilter) {
                    return;
                }
                this.mFilter = f;
                // this.mFilteredItems = null;
                AtomBinder_1.AtomBinder.refreshValue(this, "filter");
            },
            enumerable: false,
            configurable: true
        });
        AtomItemsControl.prototype.onScroll = function () {
            var _this = this;
            if (this.scrollTimeout) {
                clearTimeout(this.scrollTimeout);
            }
            this.scrollTimeout = setTimeout(function () {
                _this.scrollTimeout = 0;
                _this.onVirtualCollectionChanged();
            }, 10);
        };
        AtomItemsControl.prototype.toggleSelection = function (data) {
            this.mOnUIChanged = true;
            this.mValue = undefined;
            if (this.allowMultipleSelection) {
                if (this.mSelectedItems.indexOf(data) !== -1) {
                    AtomBinder_1.AtomBinder.removeItem(this.mSelectedItems, data);
                }
                else {
                    AtomBinder_1.AtomBinder.addItem(this.mSelectedItems, data);
                }
            }
            else {
                this.mSelectedItems.length = 1;
                this.mSelectedItems[0] = data;
                AtomBinder_1.AtomBinder.refreshItems(this.mSelectedItems);
            }
            this.mOnUIChanged = false;
        };
        AtomItemsControl.prototype.validateScroller = function () {
            var _this = this;
            if (this.mScrollerSetup) {
                return;
            }
            var ip = this.itemsPresenter;
            var e = this.element;
            var vc = this.mVirtualContainer;
            if (!vc) {
                if (ip === e && !/table/i.test(e.nodeName)) {
                    throw new Error("virtualContainer presenter not found,"
                        + "you must put itemsPresenter inside a virtualContainer in order for Virtualization to work");
                }
                else {
                    vc = this.mVirtualContainer = this.element;
                }
            }
            vc.style.overflow = "auto";
            this.bindEvent(vc, "scroll", function () {
                _this.onScroll();
            });
            ip.style.overflow = "hidden";
            // this.validateScroller = null;
            var isTable = /tbody/i.test(ip.nodeName);
            var fc;
            var lc;
            if (isTable) {
                fc = document.createElement("TR");
                lc = document.createElement("TR");
            }
            else {
                fc = document.createElement("DIV");
                lc = document.createElement("DIV");
            }
            fc.classList.add("sticky");
            fc.classList.add("first-child");
            lc.classList.add("sticky");
            lc.classList.add("last-child");
            fc.style.position = "relative";
            fc.style.height = "0";
            fc.style.width = "100%";
            fc.style.clear = "both";
            lc.style.position = "relative";
            lc.style.height = "0";
            lc.style.width = "100%";
            lc.style.clear = "both";
            this.mFirstChild = fc;
            this.mLastChild = lc;
            ip.appendChild(fc);
            ip.appendChild(lc);
            // let us train ourselves to find average height/width
            this.mTraining = true;
            this.mScrollerSetup = true;
        };
        AtomItemsControl.prototype.createChild = function (df, data) {
            var t = this.itemTemplate;
            var ac = this.app.resolve(t, true);
            var e = ac.element;
            e._logicalParent = this.element;
            e._templateParent = this;
            if (df) {
                df.appendChild(ac.element);
            }
            ac.data = data;
            this.element.dispatchEvent(new CustomEvent("item-created", {
                bubbles: false,
                cancelable: false,
                detail: data
            }));
            return ac;
        };
        AtomItemsControl.prototype.disposeChildren = function (e) {
            var en = new AtomUI_1.ChildEnumerator(e);
            while (en.next()) {
                var iterator = en.current;
                var ac = iterator.atomControl;
                if (ac) {
                    ac.dispose();
                }
            }
            e.innerHTML = "";
        };
        /** Item Template for displaying individual items */
        AtomItemsControl.itemTemplate = XNode_1.default.prepare("itemTemplate", true, true);
        return AtomItemsControl;
    }(AtomControl_1.AtomControl));
    exports.AtomItemsControl = AtomItemsControl;
    var AtomItemsControlItemTemplate = /** @class */ (function (_super) {
        __extends(AtomItemsControlItemTemplate, _super);
        function AtomItemsControlItemTemplate() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        AtomItemsControlItemTemplate.prototype.create = function () {
            var _this = this;
            this.runAfterInit(function () {
                var tp = _this.element._templateParent;
                _this.element.textContent = _this.data[tp.valuePath];
            });
        };
        return AtomItemsControlItemTemplate;
    }(AtomControl_1.AtomControl));
});
//# sourceMappingURL=AtomItemsControl.js.map