import { __assign, __extends } from "tslib";
import { BehaviorSubject, Subject } from 'rxjs';
import { hasOwnProperty } from '../../../utils/hasOwn';
import identity from '../../../utils/identity';
import isNil from '../../../utils/isNil';
import isPlainObject from '../../../utils/isPlainObject';
import omit from '../../../utils/omit';
import uniqueId from '../../../utils/uniqueId';
import { None, Some } from '../maybe';
import { ValidateOption } from '../validate';
import { warningSubscribeValid, warningSubscribeValue } from '../warnings';
import { BasicModel } from './basic';
import { isModel, SET_ID } from './is';
import { createSentinelSubject } from './sentinel-subject';
var FieldSetModel = (function (_super) {
    __extends(FieldSetModel, _super);
    function FieldSetModel(children, id) {
        if (id === void 0) { id = uniqueId('field-set-'); }
        var _this = _super.call(this, id) || this;
        _this._displayName = 'FieldSetModel';
        _this.patchedValue = null;
        _this.childRegister$ = new Subject();
        _this.childRemove$ = new Subject();
        _this.children = {};
        _this.owner = null;
        _this.invalidModels = new Set();
        _this.mapModelToSubscriptions = new Map();
        _this.normalizeBeforeSubmit = identity;
        var keys = Object.keys(children);
        var keysLength = keys.length;
        for (var index = 0; index < keysLength; index++) {
            var name_1 = keys[index];
            var child = children[name_1];
            _this.registerChild(name_1, child);
        }
        _this.children = children;
        return _this;
    }
    Object.defineProperty(FieldSetModel.prototype, "value", {
        get: function () {
            if (this._value$) {
                return this._value$.value;
            }
            return this.getRawValue();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FieldSetModel.prototype, "value$", {
        get: function () {
            return this._getValue$(true);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FieldSetModel.prototype, "valid$", {
        get: function () {
            return this._getValid$(true);
        },
        enumerable: false,
        configurable: true
    });
    FieldSetModel.prototype._getValid$ = function (shouldWarn) {
        if (shouldWarn === void 0) { shouldWarn = false; }
        warningSubscribeValid(shouldWarn, this._displayName);
        if (!this._valid$) {
            this._initValid$();
        }
        return this._valid$;
    };
    FieldSetModel.prototype._getValue$ = function (shouldWarn) {
        if (shouldWarn === void 0) { shouldWarn = false; }
        warningSubscribeValue(shouldWarn, this._displayName);
        if (!this._value$) {
            this._initValue$();
        }
        return this._value$;
    };
    FieldSetModel.prototype.initialize = function (values) {
        if (!isPlainObject(values)) {
            return;
        }
        this.initialValue = Some(values);
        var keys = Object.keys(values);
        for (var i = 0; i < keys.length; i += 1) {
            var key = keys[i];
            var child = this.children[key];
            if (isModel(child)) {
                child.initialize(values[key]);
            }
        }
    };
    FieldSetModel.prototype.getPatchedValue = function (name) {
        if (this.patchedValue && name in this.patchedValue) {
            return Some(this.patchedValue[name]);
        }
        return None();
    };
    FieldSetModel.prototype.getRawValue = function () {
        var value = {};
        var childrenKeys = Object.keys(this.children);
        for (var i = 0; i < childrenKeys.length; i++) {
            var key = childrenKeys[i];
            var model = this.children[key];
            value[key] = model.getRawValue();
        }
        return value;
    };
    FieldSetModel.prototype.getSubmitValue = function () {
        var value = {};
        var childrenKeys = Object.keys(this.children);
        for (var i = 0; i < childrenKeys.length; i++) {
            var key = childrenKeys[i];
            var model = this.children[key];
            value[key] = model.getSubmitValue();
        }
        return this.normalizeBeforeSubmit(value);
    };
    FieldSetModel.prototype.registerChild = function (name, model) {
        var children = this.children;
        var prev = children[name];
        if (prev === model) {
            return;
        }
        if (prev) {
            this.removeChild(name);
        }
        this._subscribeChild(name, model);
        model.owner = this;
        children[name] = model;
        this.childRegister$.next(name);
    };
    FieldSetModel.prototype.removeChild = function (name) {
        if (hasOwnProperty(this.children, name)) {
            var model = this.children[name];
            model.owner = null;
            this._unsubscribeChild(model);
            delete this.children[name];
            this.childRemove$.next(name);
            return model;
        }
        return null;
    };
    FieldSetModel.prototype.dispose = function () {
        var _this = this;
        var _a, _b;
        _super.prototype.dispose.call(this);
        var children = this.children;
        Object.keys(children).forEach(function (key) {
            var child = children[key];
            _this._unsubscribeChild(child);
            child.dispose();
        });
        this.childRegister$.complete();
        this.childRemove$.complete();
        (_a = this._value$) === null || _a === void 0 ? void 0 : _a.complete();
        (_b = this._valid$) === null || _b === void 0 ? void 0 : _b.complete();
        this._valid$ = createSentinelSubject(this._displayName, false);
        this._value$ = createSentinelSubject(this._displayName, {});
        this.childRegister$ = createSentinelSubject(this._displayName, '');
        this.childRemove$ = createSentinelSubject(this._displayName, '');
    };
    FieldSetModel.prototype.patchValue = function (value) {
        var _a;
        if (!isPlainObject(value)) {
            return;
        }
        this.patchedValue = value;
        var keys = Object.keys(value);
        for (var i = 0; i < keys.length; i += 1) {
            var key = keys[i];
            if (hasOwnProperty(this.children, key)) {
                (_a = this.children[key]) === null || _a === void 0 ? void 0 : _a.patchValue(value[key]);
            }
        }
    };
    FieldSetModel.prototype.clear = function () {
        var _a;
        var keys = Object.keys(this.children);
        for (var i = 0; i < keys.length; i += 1) {
            var key = keys[i];
            (_a = this.children[key]) === null || _a === void 0 ? void 0 : _a.clear();
        }
    };
    FieldSetModel.prototype.clearError = function () {
        var _a;
        this.error$.next(null);
        var children = this.children;
        var keys = Object.keys(children);
        var length = keys.length;
        for (var i = 0; i < length; i++) {
            var key = keys[i];
            (_a = children[key]) === null || _a === void 0 ? void 0 : _a.clearError();
        }
    };
    FieldSetModel.prototype.reset = function () {
        var _a;
        var keys = Object.keys(this.children);
        for (var i = 0; i < keys.length; i += 1) {
            var key = keys[i];
            (_a = this.children[key]) === null || _a === void 0 ? void 0 : _a.reset();
        }
    };
    FieldSetModel.prototype.validate = function (option) {
        var _this = this;
        if (option === void 0) { option = ValidateOption.Default; }
        if (option & ValidateOption.IncludeChildrenRecursively) {
            var childOption_1 = option | ValidateOption.StopPropagation;
            return Promise.all(Object.keys(this.children)
                .map(function (key) { return _this.children[key].validate(childOption_1); })
                .concat(this.triggerValidate(option)));
        }
        return this.triggerValidate(option);
    };
    FieldSetModel.prototype.pristine = function () {
        var keys = Object.keys(this.children);
        for (var i = 0; i < keys.length; i += 1) {
            var key = keys[i];
            var child = this.children[key];
            if (!child.pristine()) {
                return false;
            }
        }
        return true;
    };
    FieldSetModel.prototype.dirty = function () {
        return !this.pristine();
    };
    FieldSetModel.prototype.touched = function () {
        var keys = Object.keys(this.children);
        for (var i = 0; i < keys.length; i += 1) {
            var key = keys[i];
            var child = this.children[key];
            if (child.touched()) {
                return true;
            }
        }
        return false;
    };
    FieldSetModel.prototype.get = function (name) {
        return this.children[name];
    };
    FieldSetModel.prototype._setValid = function () {
        var _a;
        (_a = this._valid$) === null || _a === void 0 ? void 0 : _a.next(isNil(this.error) && !this.invalidModels.size);
    };
    FieldSetModel.prototype._initValue$ = function () {
        var _this = this;
        var value$ = new BehaviorSubject({});
        this._value$ = value$;
        for (var _i = 0, _a = Object.entries(this.children); _i < _a.length; _i++) {
            var _b = _a[_i], name_2 = _b[0], model = _b[1];
            this._subscribeChild(name_2, model);
        }
        var _c = this, childRegister$ = _c.childRegister$, childRemove$ = _c.childRemove$;
        childRegister$.subscribe(function (name) {
            var _a;
            value$.next(__assign(__assign({}, value$.value), (_a = {}, _a[name] = _this.children[name].getRawValue(), _a)));
        });
        childRemove$.subscribe(function (name) {
            value$.next(omit(value$.value, [name]));
        });
    };
    FieldSetModel.prototype._initValid$ = function () {
        var _this = this;
        this._valid$ = new BehaviorSubject(isNil(this.error));
        var $ = this.error$.subscribe(function () {
            _this._setValid();
        });
        this.mapModelToSubscriptions.set(this, [$]);
        for (var _i = 0, _a = Object.entries(this.children); _i < _a.length; _i++) {
            var _b = _a[_i], name_3 = _b[0], model = _b[1];
            this._subscribeChild(name_3, model);
        }
    };
    FieldSetModel.prototype._subscribeChild = function (name, model) {
        var _this = this;
        var _a = this, invalidModels = _a.invalidModels, _valid$ = _a._valid$, _value$ = _a._value$;
        if (_valid$) {
            this._subscribeObservable(model, model._getValid$(), function (valid) {
                if (valid) {
                    invalidModels.delete(model);
                }
                else {
                    invalidModels.add(model);
                }
                _this._setValid();
            });
        }
        if (_value$) {
            this._subscribeObservable(model, model._getValue$(), function (childValue) {
                var _a;
                _value$.next(__assign(__assign({}, _value$.value), (_a = {}, _a[name] = childValue, _a)));
            });
        }
    };
    FieldSetModel.prototype._unsubscribeChild = function (model) {
        var subs = this.mapModelToSubscriptions.get(model);
        subs === null || subs === void 0 ? void 0 : subs.forEach(function (sub) { return sub.unsubscribe(); });
        this.mapModelToSubscriptions.delete(model);
        this.invalidModels.delete(model);
        this._setValid();
    };
    FieldSetModel.prototype._subscribeObservable = function (model, observable, observer) {
        var mapModelToSubscriptions = this.mapModelToSubscriptions;
        var $ = observable.subscribe(observer);
        var subs = mapModelToSubscriptions.get(model);
        if (subs) {
            subs.push($);
        }
        else {
            mapModelToSubscriptions.set(model, [$]);
        }
    };
    return FieldSetModel;
}(BasicModel));
FieldSetModel.prototype[SET_ID] = true;
export { FieldSetModel };
