import * as React from "react";
var ContentChildrenManager = /** @class */ (function () {
    function ContentChildrenManager(getPropsKey, getKey, updateContentChildren) {
        this._contentChildren = null;
        this._contentChildrenActual = null;
        this._contentChildrenMap = null;
        this._contentChildrenUnresolved = 0;
        this.getChildRef = this.getChildRef.bind(this);
        this._getPropsKey = getPropsKey;
        this._getKey = getKey;
        this._updateContentChildren = updateContentChildren;
    }
    ContentChildrenManager.prototype.getChildren = function (propChildren) {
        var _this = this;
        var children = [];
        React.Children.forEach(propChildren, function (ch) {
            var key = _this._getPropsKey(ch);
            if (key === undefined) {
                throw new Error("each child must have a unique key or name property");
            }
            children.push(React.cloneElement(ch, {
                key: key,
                ref: _this.getChildRef
            }));
        });
        this._contentChildren = children;
        var prevActual = this._contentChildrenActual;
        this._contentChildrenActual = [];
        var prevMap = this._contentChildrenMap;
        this._contentChildrenMap = new Map();
        this._contentChildrenUnresolved = 0;
        if (this._contentChildren) {
            this._contentChildren.map(function (ch, i) {
                var key = _this._getPropsKey(ch);
                if (prevMap && prevMap.has(key)) {
                    _this._contentChildrenActual[i] = prevActual[prevMap.get(key)];
                }
                else {
                    _this._contentChildrenActual[i] = null;
                    _this._contentChildrenUnresolved++;
                }
                _this._contentChildrenMap.set(key, i);
            });
        }
        return children;
    };
    ContentChildrenManager.prototype.getChildRef = function (child) {
        //console.log(child);
        this.trackChild(child);
    };
    Object.defineProperty(ContentChildrenManager.prototype, "contentChildrenActual", {
        get: function () {
            return this._contentChildrenActual;
        },
        enumerable: true,
        configurable: true
    });
    ContentChildrenManager.prototype.trackChild = function (child) {
        if (child === null) {
            return;
        }
        var name = this._getKey(child);
        var index = this._contentChildrenMap.get(name);
        if (this._contentChildrenActual[index] === null) {
            this._contentChildrenActual[index] = child;
            this._contentChildrenUnresolved--;
            if (this._contentChildrenUnresolved <= 0) {
                this._updateContentChildren();
            }
        }
    };
    return ContentChildrenManager;
}());
export { ContentChildrenManager };
